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

时间:2016-05-21 14:02:55

标签: c# xml attributes

我浏览了互联网,但我无法找到解决问题的方法,不过我觉得这应该很简单。

我有一个XML文档。有两个节点看起来像:

<Attachments>
  </Attachments>

 <Templates>
  </Templates>

向每个节点添加两个元素后,它们应如下所示:

<Attachments>
        <Attachment INDEX0="Test1" />
        <Attachment INDEX1="Test2" />
      </Attachments>

     <Templates>
        <Template INDEX0="Test1">EMPTY</Template>
        <Template INDEX0="Test2">EMPTY</Template>
      </Templates>

我尝试了第一个代码:

 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);
    }

但这绝对没有。我怎样才能实现这两种情况?

谢谢!

2 个答案:

答案 0 :(得分:1)

我建议使用LINQ to XML,除非你有特殊原因不能。使用旧的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);

有关正常工作的演示,请参阅this fiddle

答案 1 :(得分:0)

抱歉,我发现了错误。 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);
        }

但我仍然不知道如何在我的示例中使用template属性来实现这种情况。

相关问题