2

请我尝试将数据插入 xml,这是插入数据后我的 xml 文件的当前格式

<?xml version="1.0" encoding="utf-8"?>
<ApplicationData>
        <Minutes>

        </Minutes>

        <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" />
        <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" /> 

</ApplicationData>

使用下面的代码

XmlTextReader _xmlTextReader = new XmlTextReader(config.XMLPath);
                XmlDocument _xmlDocument = new XmlDocument();
                _xmlDocument.Load(_xmlTextReader);
                //Note: Close the reader object to release the xml file. Else while saving you will get an error that it is 
                //being used by another process.
                _xmlTextReader.Close();

                XmlElement _minutesElement = _xmlDocument.CreateElement("Minute");
                _minutesElement.SetAttribute("MinuteId", "6");
                _minutesElement.SetAttribute("Title", "Project6");
                _minutesElement.SetAttribute("Date", "6");
                _minutesElement.SetAttribute("Time", "Project6");
                _minutesElement.SetAttribute("Location", "6");
                _minutesElement.SetAttribute("MinuteDocumentFile", "Project6");

                _xmlDocument.DocumentElement.AppendChild(_minutesElement);
                _xmlDocument.Save(config.XMLPath);

上面的代码工作正常,但我现在的挑战是,我正在尝试实现下面显示的当前 xml 格式

<?xml version="1.0" encoding="utf-8"?>
<ApplicationData>
        <Minutes>
             <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" />
             <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" /> 
        </Minutes>
</ApplicationData>

我想将创建的“分钟”XmlElement 存储在“分钟”元素内,而不是在它之外。

谢谢..

4

2 回答 2

1
var doc = XElement.Load(config.XMLPath);
var target = doc.Descendants("Minutes").First();
target.Add(new XElement("Minute", new XAttribute("MinuteId", 6), new ...));
doc.Save(config.XMLPath);
于 2017-10-24T13:03:24.097 回答
1

线

_xmlDocument.DocumentElement.AppendChild(_minutesElement);

只是将您的新 _minutesElement 附加到树的末尾。您需要告诉它您希望它属于哪个元素。

改为:

_xmlDocument.DocumentElement["Minutes"].AppendChild(_minutesElement);

给出:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationData>
  <Minutes>
    <Minute MinuteId="6" Title="Project6" Date="6" Time="Project6" Location="6" MinuteDocumentFile="Project6" />
  </Minutes>
</ApplicationData>
于 2017-10-24T12:58:56.720 回答