簡體   English   中英

C#中的XML過濾

[英]XML filtering in C#

我有一個源XML文件。 我為用戶提供了一個UI,用於選擇他們想要包含在結果XML中的元素。 UI的工作原理是加載XSD文件並在復選框樹中顯示元素。 然后,用戶可以檢查他們需要的元素。

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>

當我們創建一個用戶友好的工具來處理我們的服務器配置文件(它們不是用戶友好的XML)時,我們選擇將用戶選擇(與默認配置的差異)直接存儲為XSL轉換。

在您的情況下,這應該也可以,但它取決於XML的確切結構。 如果您的原始XML是類似的

<data>
  <item id="1">...</item>
  <item id="2">...</item>
  ...
</data>

您可以將選擇存儲為例如:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/data">
    <data>
        <xsl:apply-templates select="item" />
    </data>
    </xsl:template>

    <xsl:template match="item[@id='1']">
    <xsl:copy-of select="."/>
    </xsl:template>
    <xsl:template match="item[@id='3']">
    <xsl:copy-of select="."/>
    </xsl:template>
    <xsl:template match="item[@id='4']">
    <xsl:copy-of select="."/>
    </xsl:template>

    <xsl:template match="node()" />
</xsl:stylesheet>

這很簡單,你的工具應該能夠加載它並讓用戶修改他的選擇。

處理在很大程度上取決於您未顯示的XML結構。

它可以這么簡單

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pWanted" select="'|A|C|'"/>

 <xsl:template match="node()|@*" name="identity">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="*/*">
   <xsl:if test="contains($pWanted, concat('|',name(), '|'))">
    <xsl:call-template name="identity"/>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

當此轉換應用於以下XML文檔時

<t>
    <A>1</A>
    <B>2</B>
    <C>3</C>
</t>

生成所需的正確結果 (只有用戶指定的元素AC保留在輸出中):

<t>
   <A>1</A>
   <C>3</C>
</t>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM