2012-11-06 51 views
1

我需要將某些XML注入某個節點下的預先存在的XML文件中。下面是我要創建我的XML代碼:如何根據XML文檔的屬性值和XElement對象獲取節點?

//Define the nodes 
XElement dataItemNode = new XElement("DataItem"); 
XElement setterNodeDisplayName = new XElement("Setter"); 
XElement setterNodeOU = new XElement("Setter"); 

//Create the tree with the nodes 
dataItemNode.Add(setterNodeDisplayName); 
dataItemNode.Add(setterNodeOU); 

//Define the attributes 
XAttribute nameAttrib = new XAttribute("Name", "OrganizationalUnits"); 
XAttribute displayNameAttrib = new XAttribute("Property", "DisplayName"); 
XAttribute ouAttrib = new XAttribute("Property", "OU"); 

//Attach the attributes to the nodes 
setterNodeDisplayName.Add(displayNameAttrib); 
setterNodeOU.Add(ouAttrib); 

//Set the values for each node 
setterNodeDisplayName.SetValue("TESTING DISPLAY NAME"); 
setterNodeOU.SetValue("OU=funky-butt,OU=super,OU=duper,OU=TMI,DC=rompa-room,DC=pbs,DC=com"); 

下面是我到目前爲止加載了XML文檔,並試圖獲取我需要插入下我的XML節點代碼:

//Load up the UDI Wizard XML file 
XDocument udiXML = XDocument.Load("UDIWizard_Config.xml"); 

//Get the node that I need to append to and then append my XML to it 
XElement ouNode = THIS IS WHAT I DONT KNOW HOW TO DO 
ouNode.Add(dataItemNode); 

這裏是從現有的文件我想工作與XML:

<Data Name="OrganizationalUnits"> 
     <DataItem> 
      <Setter Property="DisplayName">TESTING DISPLAY NAME</Setter> 
      <Setter Property="OU">OU=funky-butt,OU=super,OU=duper,OU=TMI,DC=rompa-room,DC=pbs,DC=com</Setter> 
     </DataItem> 

我有多個節點,與「數據」的名字,但我需要得到的是節點,我不知道如何。只要學習如何在C#中使用XML。

謝謝。

回答

3

這將讓第一Data節點與Name屬性匹配OrganizationalUnits

var ouNode = udiXML 
    .Descendants("Data") 
    .Where(n => n.Attribute("Name") != null) 
    .Where(n => n.Attribute("Name").Value == "OrganizationalUnits") 
    .First(); 

如果您的文檔可能包含Data節點沒有Name屬性,空額外的檢查可能是必要的。

注意,您可以實現使用XPath相同的結果(這將選擇根Data節點,您可以使用Element方法DataItem節點獲取):

var ouNode = udiXML.XPathSelectElement("//Data[@Name = 'OrganizationalUnits']"); 
+0

它實際上就比遠一點和返回那是在下面。 – Dbloom

+0

使用Xpath的第二個例子讓我得到了我想要的。非常感謝! – Dbloom