I have an XML file and want to extract some nodes of it in a new XML file and save it. The XML file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<files version="2.1.8" Dir="D:Test\Exm_2" modified="2016-03-18 23:14:58Z" user="Test" language="en">
<file name="1">
<file name="4">
<file name="9">
</file>
</file>
</file>
<file name="2">
</file>
<test name="3">
<test name="5">
<test name="7">
</test>
</test>
</test>
</files>
My aim is that to save some special nodes(here test nodes) of this XML file. The idea is to save the root attribute attached with it as well. I mean if I want to save nodes test
in a new file I want to have the root attribute as the original XML file as:
<?xml version="1.0" encoding="utf-8"?>
<files version="2.1.8" Dir="D:Test\Exm_2" modified="2016-03-18 23:14:58Z" user="Test" language="en">
<tests>
<test name="3">
<test name="5">
<test name="7">
</test>
</test>
</test>
</tests>
</files>
But I failed to save its attribute. My code for saving the second XML file is
public void Creat_Steps(string xmlfile, string FileName)
{
XElement doc = XElement.Load(xmlfile);
var item = doc.XPathSelectElement("//test");
XElement newDoc = new XElement("files", new XElement("tests", item));
XElement Docc = new XElement("files", item);
Docc.Save(FileName + ".xml");
}
But this code create only a root node with name files
without any attribute. I have to use the attribute in the new XML file and then have not it. Any ideas?
Thanks in advance!
The simplest approach would just be to replace the child nodes of the root element instead:
var root = XElement.Load(xmlFile);
root.ReplaceNodes(new XElement("tests", root.Elements("test")));
root.Save(FileName + ".xml");
Note that there's no need for XPath here either :) Also note that I'm using Elements
rather than Descendants
, otherwise each test
element will become a new immediate child of tests
, which isn't what you want.
I'd personally suggest using XDocument
to load and save documents, as that clearly states your intent, btw. At that point you'd use
var doc = XDocument.Load(xmlFile);
doc.Root.ReplaceNodes(...);
doc.Save(...);
See more on this question at Stackoverflow