2017-05-30 56 views
0

我想在根元素下面添加子元素,但要作为第一个子元素。我现在的XML是这样使用XmlDocument在xml中添加子元素C#

<?xml version="1.0" encoding="utf-8"?> 
<testsuites> 
<testsuite name="classname" tests="9" failures="3" errors="6" time="2919" disabled="0" skipped="0"> 
    <testcase name="Setup1" time="5" classname="classname"> 
    </testcase> 
    <testcase name="Setup2" time="49" classname="classname"> 
    </testcase> 
    <testcase name="Setup3" time="357" classname="classname"> 
    </testcase> 
</testsuite> 
</testsuites> 

添加后的元素,我希望它看起来像这样

<?xml version="1.0" encoding="utf-8"?> 
<testsuites> 
<properties name ="namedata" value="valuedata"> 
</properties> 
    <testsuite name="classname" tests="9" failures="3" errors="6" time="2919" disabled="0" skipped="0"> 
    <testcase name="Setup1" time="5" classname="classname"> 
    </testcase> 
    <testcase name="Setup2" time="49" classname="classname"> 
    </testcase> 
    <testcase name="Setup3" time="357" classname="classname"> 
    </testcase> 
    </testsuite> 
</testsuites> 

我所做的是

XmlDocument report = new XmlDocument(); 
report.Load(fileOfReport); 
XmlElement root = report.CreateElement("properties"); 
root.SetAttribute("property name", "namedata"); 
root.SetAttribute("value","valuedata"); 
var items = report.GetElementsByTagName("testsuite"); 
for(int i=0; i<items.Count; i++){ 
    child.AppendChild(items[i]); 
} 
report.AppendChild(root); 
report.Save(fileOfReport); 

的代码显示性能作为根元素其中包括测试套件,但实际上我希望它作为一个与测试套件平行的儿童elemetns。我应该如何重构? 注意,我只能用XMLDOCUMENT没有的XDocument

感谢

+0

属性名称不能包含空格。这就是'0x20'。将'property name'更改为'propertyName',它应该可以正常工作。 – MarcinJuraszek

+0

首先验证您正在使用的XML。然后将新的孩子添加到它。 –

+0

谢谢@MarcinJuraszek。你的回答是对的。我纠正它。但我有另一个问题。我已经更新了这个问题。非常感谢 –

回答

0

XmlDocument有很多有用的方法。在这种情况下,PrependChild很方便。

XmlDocument report = new XmlDocument(); 
report.Load(fileOfReport); 

XmlElement root = report.CreateElement("properties"); 
root.SetAttribute("propertyname", "namedata"); 
root.SetAttribute("value", "valuedata"); 

report.DocumentElement.PrependChild(root); 

report.Save(fileOfReport); 
+0

看起来像PrependChild是正确的调用方法。但我运行你的解决方案,它仍然在xml中缺少。它只显示<属性值属性名称> –

+0

@JiangJiali - 我刚刚复制了你的代码创建元素。显示有效的XML,所以我可以编写它的创建代码。你的xml在这个问题上是不正确的。 –

+0

请看我的xml文件的第二部分,这是我想要的。 –

相关问题