2016-05-30 69 views
1

我有下面的XMl文件,我想提取它的一些節點。我想提取兩組節點。如何提取XML文件的兩個不同節點

<root > 
    <comment> 
    // something here 
    </comment> 
    <define> 
    // something here 
    </define> 
    <scrp> 
    // something here 
    </scrp> 
    <files > 
    <file id ="1" Name="S1"> 
    <file id ="2" Name="S11"> 
     <file id ="3" Name="S111" /> 
     <file id ="4" Name="S112" /> 
     <file id ="5" Name="S1121" /> 
    </file > 
    <file id ="6" Name="S12" /> 
    </file > 
</files> 
</root > 

我想所有節點filesscrp提取到新XML文件。我做了如下代碼,但它只會保存files節點,而不是節點filesscrp。我可以問你的幫忙嗎?

var doc = XDocument.Load(xmlfile); 
XElement files = doc.Descendants("files").FirstOrDefault(); 
XElement root = doc.Element("root"); 
doc.Element("root").ReplaceWith(new XElement("root", new object[] { pack.Attributes(), files })); 
doc.Root.ReplaceNodes(new XElement("files", doc.Descendants("file"))); 

回答

0

如果需要用特定節點替換根節點的全部內容,則應該使用doc.Root上的ReplaceAll。這是你想要達到的目標嗎?

 var doc = XDocument.Load(xmlfile); 
     XElement files = doc.Descendants("files").FirstOrDefault(); 
     XElement scrp = doc.Descendants("scrp").FirstOrDefault(); 
     doc.Root.ReplaceAll(scrp, files);