Skip to main content
 首页 » 编程设计

c#之C# 中的 XML 过滤

2024年02月23日19wuhuacong

我有一个源 XML 文件。我为用户提供了一个 UI 来选择他们想要包含在生成的 XML 中的元素。 UI 的工作原理是加载 XSD 文件并在 checkbox tree 中呈现元素。 .然后用户可以检查他们需要的元素。

UI 工作正常,但我需要一些关于后端逻辑的建议/指导:基本上我想对源 xml“应用过滤器”,但是

  1. 我应该如何保存用户的选择(以分隔符分隔值或??)和
  2. 我应该如何应用这个“过滤器”(也许使用 XSLT)?

编辑: src xml 结构如下所示:

<IDs> 
  <id1></id1> 
  <id2></id2> 
  ... 
</IDs> 
<Traveler> 
  <name></name> 
  <email></email> 
  ... 
<Traveler> 
<Segments> 
  <Segment i:type="Air"> 
    <carrier></carrier> 
    ... 
  </Segment> 
  <Segment i:type="Hotel"> 
    <supplier></supplier> 
    ... 
  </Segment> 
</Segments> 
<Notes> 
... 
</Notes> 

EDIT2:所有这些元素都可以选中/取消选中以包含在生成的 xml 中。

请您参考如下方法:

如果您真的想使用 XSLT 执行此操作,请尝试这种方法。它复制与您添加到第二个模板的任何 XPath 表达式都不匹配的所有元素和属性。您必须动态生成 XSLT 并进行编译,因此速度不会特别快:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
 
    <xsl:output method="xml" indent="yes"/> 
 
    <xsl:template match="@* | node()"> 
        <xsl:copy> 
            <xsl:apply-templates select="@* | node()"/> 
        </xsl:copy> 
    </xsl:template> 
 
    <xsl:template match="XPath for all non-selected elements"></xsl:template> 
</xsl:stylesheet>