I am new to c#. Right now I am trying to get the name of some specific elements in an xml file and create a new xml file for these. I have tried with LINQ, so that I can parse the xml and get the name of some elments that I want. I do not want to use console.writeline to output this name. Instead I would like to create a new xml file and save these names in it. Can anyone give me some tips? The following is example data I would like to parse:
<root>
<Package>
<Class name="EnterpriseArchitect">
<Operation/>
</Class>
<Class name="ZachmanFramework">
<Operation/>
</Class>
</Package>
</root>
I want to get the attribute name of the element Class and save it in a new xml file like this:
<root>
<EnterpriseArchitect/>
<ZachmanFramework/>
</root>
The following is my c# code, but I can not reach the goal:
XDocument xdoc = XDocument.Load(@"C:\Users\jsc\Desktop\123456.xml");
XDocument xNew = new XDocument();
var datatype = xdoc.Root.Elements("Package").Elements("Class")
foreach (var dut in datatype)
{
var dataTypeName = dut.Attribute("name").Value;
xNew.Add(new XElement(dataTypeName));
}
xNew.Save(@"C:\Users\jsc\Desktop\1234567.xml");
Please, read my comments to the question.
This should work:
XDocument srcdoc = XDocument.Load("sourceFileName.xml");
List<XElement> names = srcdoc.Descendants("Class")
.Select(x=> new XElement(x.Attribute("name").Value))
//.Distinct() //uncomment this if duplicate values aren't allowed
.ToList();
XDocument newdoc = new XDocument();
XElement root = new XElement("root");
root.Add(names);
newdoc.Add(root);
newdoc.Save("newFileName.xml");
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.