2009-03-02 46 views

回答

4

使用XmlDocument,您将需要将这些节点导入第二个文档;

XmlDocument doc = new XmlDocument(); 
    XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("root")); 
    XmlNodeList list = // your query 
    foreach (XmlElement child in list) 
    { 
     root.AppendChild(doc.ImportNode(child, true)); 
    } 
+0

这到底是我去了答案。 – 2009-03-03 11:37:41

0

我刚才想到了一个这样做的方法,但它看起来并不很优雅。

使用StringBuilder的OuterXml结合各自的XmlNodeList中的将XMLNode的...

正如我说这是不雅,但我认为它可能工作。我会很感激任何其他建议...

1

这是使用XSLT,这是一种用于将一个XML文档转换成另一个(或到HTML或文字),高效率和强大的工具,一个非常典型的原因。

这里有一个最小的程序来执行XSLT转换并将结果发送到控制台:

using System; 
using System.Xml; 
using System.Xml.Xsl; 

namespace XsltTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      XslCompiledTransform xslt = new XslCompiledTransform(); 
      xslt.Load("test.xslt"); 

      XmlWriter xw = XmlWriter.Create(Console.Out); 
      xslt.Transform("input.xml", xw); 
      xw.Flush(); 
      xw.Close(); 

      Console.ReadKey(); 
     } 
    } 
} 

这里的实际XSLT,这是在程序目录保存在test.xslt。这很简单:给定一个输入文档,其顶层元素名为input,它会创建一个output元素并将其复制到其属性设置为的每个子元素上。

<?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="/input"> 
     <output> 
     <xsl:apply-templates select="*[@value='true']"/> 
     </output> 
    </xsl:template> 

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

而这里的input.xml

<?xml version="1.0" encoding="utf-8" ?> 
<input> 
    <element value="true"> 
    <p>This will get copied to the output.</p> 
    <p>Note that the use of the identity transform means that all of this content 
    gets copied to the output simply because templates were applied to the 
    <em>element</em> element. 
    </p> 
    </element> 
    <element value="false"> 
    <p>This, on the other hand, won't get copied to the output.</p> 
    </element> 
</input> 
+0

这将是,但我是动态过滤,所以我不知道我需要过滤它。 XSLT +1,非常酷。 – 2009-03-03 11:19:56

相关问题