2017-05-30 101 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文件的第二部分,這是我想要的。 –