简体   繁体   English

在C#中将属性和字符串添加到XML文件

[英]Add attribute and string to XML File in c#

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. 我有一个XML文档。 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! 谢谢!

I'd suggest using LINQ to XML unless you have a specific reason you can't. 我建议您使用LINQ to XML,除非您有特定的原因不能这样做。 The old XmlDocument API is quite painful to work with: 旧的XmlDocument API很难使用:

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. 请参阅此小提琴以获得有效的演示。

Sorry, I found the error. 抱歉,我发现了错误。 The foreach loop should look like: foreach循环应如下所示:

        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. 但在我的示例中,我仍然不知道如何使用template属性来实现此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM