2016-01-12 123 views
0

我有下面的xdocument。在xdocument中的其他屬性之前添加屬性

<setup name="NEW"> 
    <master comment="" gui_namewidth="160" gui_valwidth="40" name="MASTER" type="u8"> 
     <item comment="" name="Name" value="0"/> 
    </master> 
    <enum comment="" gui_namewidth="160" gui_valwidth="40" name="Name" type="u8"> 
     <item comment="" name="1" value="0"/> 
    </enum> 
</setup> 

現在我想一個新的屬性crc添加到setup節點,這CRC應該是屬性列表,即在第一屬性所得的XDocument應該是這樣的

<setup CRC = "0x1244343" name="NEW"> 
    <master comment="" gui_namewidth="160" gui_valwidth="40" name="MASTER" type="u8"> 
     <item comment="" name="Name" value="0"/> 
    </master> 
    <enum comment="" gui_namewidth="160" gui_valwidth="40" name="Name" type="u8"> 
     <item comment="" name="1" value="0"/> 
    </enum> 
</setup> 

因爲需要爲了向後兼容第一屬性,這將計算的父節點的相同的CRC作爲前添加。

+0

不能看到你的XDocument將得到的? – Megha

+0

您需要正確格式化您的問題,特別是xml。這次我已經爲你做了,但將來請看預覽或最終問題頁面,並根據需要進行編輯。 – AakashM

+0

Isnt CRC是作爲第一個屬性添加的嗎?我期望它這樣做,因爲它應該按字母順序生成屬性,而在您的情況下,第二個屬性以「n」開頭。 – Megha

回答

1

試試這個

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string xml = 
       "<setup name=\"NEW\">" + 
        "<master comment=\"\" gui_namewidth=\"160\" gui_valwidth=\"40\" name=\"MASTER\" type=\"u8\">" + 
         "<item comment=\"\" name=\"Name\" value=\"0\"/>" + 
        "</master>" + 
        "<enum comment=\"\" gui_namewidth=\"160\" gui_valwidth=\"40\" name=\"Name\" type=\"u8\">" + 
         "<item comment=\"\" name=\"1\" value=\"0\"/>" + 
        "</enum>" + 
       "</setup>"; 


      XDocument doc = XDocument.Parse(xml); 
      XElement setup = doc.Element("setup"); 
      setup.ReplaceAttributes(new object[] { new XAttribute("CRC", "0x1244343"), setup.Attributes() }); 
     } 
    } 
} 
+0

非常感謝。它完美的作品。 –