Reputation: 559
I looked around the internet but I can't find a solution for my problem, although I guess this should be very simple.
I have a XML document. There two nodes that look like:
<Attachments>
</Attachments>
<Templates>
</Templates>
After adding two elements to each node, they should look like:
<Attachments>
<Attachment INDEX0="Test1" />
<Attachment INDEX1="Test2" />
</Attachments>
<Templates>
<Template INDEX0="Test1">EMPTY</Template>
<Template INDEX0="Test2">EMPTY</Template>
</Templates>
I tried following code for the first one:
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Directory.GetCurrentDirectory(), "test.xml"));
XmlElement root = doc.DocumentElement;
XmlNode node = root.SelectSingleNode("//Attachments");
List<String> list = new List<string>() {"Test1","Test2"};
foreach(var item in list)
{
XmlElement elem = doc.CreateElement("Attachment");
root.AppendChild(elem);
XmlNode subNode = root.SelectSingleNode("Attachment");
XmlAttribute xKey = doc.CreateAttribute(string.Format("INDEX{0}", list.IndexOf(item).ToString()));
xKey.Value = item;
subNode.Attributes.Append(xKey);
}
but this does absolutely nothing. How can I achieve these two cases?
Thank you!
Upvotes: 0
Views: 734
Reputation: 26213
I'd suggest using LINQ to XML unless you have a specific reason you can't. The old XmlDocument
API is quite painful to work with:
var items = new List<string> {"Test1", "Test2"};
var attachments = items.Select((value, index) =>
new XElement("Attachment", new XAttribute("INDEX" + index, value)));
var doc = XDocument.Load(@"path/to/file.xml");
doc.Descendants("Attachments")
.Single()
.Add(attachments);
See this fiddle for a working demo.
Upvotes: 2
Reputation: 559
Sorry, I found the error. The foreach loop should look like:
foreach(var item in list)
{
XmlElement elem = doc.CreateElement(string.Format("Attachment{0}", list.IndexOf(item)));
node.AppendChild(elem);
XmlNode subNode = root.SelectSingleNode(string.Format("//Attachment{0}", list.IndexOf(item)));
XmlAttribute xKey = doc.CreateAttribute(string.Format("INDEX{0}", list.IndexOf(item).ToString()));
xKey.Value = item;
subNode.Attributes.Append(xKey);
}
but I still don't know how to achieve the case with the template attribute in my example.
Upvotes: 0