【问题标题】:Merge two xml file nodes with same node value合并两个具有相同节点值的 xml 文件节点
【发布时间】:2015-04-11 10:27:54
【问题描述】:

我想在 C# 或 XSLT 中合并两个 xml 文件的节点。如果两个不同xml文件的Method节点的Path值相同。两个 Method 节点应该在输出中合并为一个。

示例: 文件1:

<Methods>
<Method>
<ID>1234</ID>
<Name>manager</Name>
<Path>path1</Path>
</Method>
</Methods>

文件2:

<Methods>
<Method>
  <Path>path1</Path>
  <Description>text</Description>
</Method>
</Methods>

输出:

<Methods>
  <Method>
    <ID>1234</ID>
    <Name>manager</Name>
    <Description>text</Description>
  </Method>
</Methods>

【问题讨论】:

标签: c# xml xslt


【解决方案1】:

试试这个方法?

XSLT 1.0

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

<xsl:variable name="file2" select="document('file2.xml')" />

<xsl:key name="method-by-path" match="Method" use="Path" />

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

<xsl:template match="Method">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:variable name="path" select="Path"/>
        <!-- switch context to the other file -->
        <xsl:for-each select="$file2">
            <xsl:copy-of select="key('method-by-path', $path)/*[not(self::Path)]" />
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

注意:这不会检查重复节点。

【讨论】:

    【解决方案2】:

    LINQ to XML 非常有效。试试

    var xml1 = XDocument.Load("File1.xml");
    var xml2 = XDocument.Load("File2.xml");
    
    foreach (XElement metNode in xml1.Descendants("ID"))
    {
       metNode.AddAfterSelf(xml2.Descendants("Path").Where(ele => ele.Value.Equals(metNode.Parent.Element("Path").Value)).FirstOrDefault().Parent.Element("Description"));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多