I have a List<string>
"sampleList" which contains
Data1 Data2 Data3...
The file structure is like
<file> <name filename="sample"/> <date modified =" "/> <info> <data value="Data1"/> <data value="Data2"/> <data value="Data3"/> </info> </file>
I'm currently using XmlDocument to do this.
Example:
List<string> lst; XmlDocument XD = new XmlDocument(); XmlElement root = XD.CreateElement("file"); XmlElement nm = XD.CreateElement("name"); nm.SetAttribute("filename", "Sample"); root.AppendChild(nm); XmlElement date = XD.CreateElement("date"); date.SetAttribute("modified", DateTime.Now.ToString()); root.AppendChild(date); XmlElement info = XD.CreateElement("info"); for (int i = 0; i < lst.Count; i++) { XmlElement da = XD.CreateElement("data"); da.SetAttribute("value",lst[i]); info.AppendChild(da); } root.AppendChild(info); XD.AppendChild(root); XD.Save("Sample.xml");
How can I create the same XML structure using XDocument?
The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.
XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.
LINQ to XML allows this to be much simpler, through three features:
So here you can just do:
void Main() { List<string> list = new List<string> { "Data1", "Data2", "Data3" }; XDocument doc = new XDocument( new XElement("file", new XElement("name", new XAttribute("filename", "sample")), new XElement("date", new XAttribute("modified", DateTime.Now)), new XElement("info", list.Select(x => new XElement("data", new XAttribute("value", x))) ) ) ); doc.Save("Sample.xml"); }
I've used this code layout deliberately to make the code itself reflect the structure of the document.
If you want an element that contains a text node, you can construct that just by passing in the text as another constructor argument:
// Constructs <element>text within element</element> XElement element = new XElement("element", "text within element");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With