将XML元素添加到xml文件C#中的现有XML元素

时间:2017-10-24 12:46:19

标签: c# xml nsxmlelement

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

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 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>

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

if XCUIApplication().otherElements[XYZ].exists { while !XCUIApplication().buttons[Button].exists { 
XCUIApplication().otherElements[XYZ].swipeLeft() } 
XCTAssertTrue(XCUIApplication().buttons[Button].exists, "Button not exist!") XCUIApplication().buttons[Button].tap() 
}

我想将创建的“Minute”XmlElement存储在“Minutes”元素中,而不是在它之外。

谢谢..

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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);