2015-02-11 99 views
0

鑑於以下XML:C#:獲取屬性的的XPath對於XML元素

<enrollment> 
    <school> 
     <students> 
      <studentA fname="John" lname="Doe" age="23" /> 
      <studentB fname="Mary" lname="Johnson" age="22" /> 
     </students> 
    </school> 
</enrollment> 

,這裏是我的代碼來遍歷屬性 -

foreach(XmlAttribute attr in node.Attributes) 
{ 
    //--get the XPath for each attribute 
} 

其中節點= 「studentA」我如何獲得每個屬性的XPath?

編輯: 基本上我想在這裏實現的是比較兩個節點是否相同。所以我必須檢查他們是否有相同的名稱,屬性和屬性值。因此,給定一個節點,我需要一個符合條件的xpath表達式。

+0

檢查他們是否具有「**相同名稱,屬性和屬性值**」的哪個部分需要知道屬性的XPath? – JLRishe 2015-02-11 05:55:25

+0

@JLRishi我忘了提及要比較的兩個節點來自不同的XML文件。給定xml1上的節點,我將獲取其xpath並使用它來查找xml2上是否存在類似的節點。但嘿謝謝你澄清事情,我意識到我真正需要的是節點的xpath,屬性是xpath表達式的條件。 – jmc 2015-02-11 06:03:49

回答

2

,你可以直接把它作爲像所有studentA節點 -

Xpath- "//studentA"

或迭代一個特定節點 - Xpath- "enrollment/school/students/studentA"

如果你想找到屬性FNAME

Xpath- "enrollment/school/students/studentA[@fname]"

Assum ING myXml是你的XmlDocument 可以遍歷特定節點屬性喜歡 -

 System.Xml.XmlNode xn = myXml.SelectSingleNode("enrollment/school/students/studentA"); 
     foreach (System.Xml.XmlAttribute attrib in xn.Attributes) 
     { 
      // find attribute name using attrib.Name 
      string sAttribName = attrib.Name; 
      if (sAttribName == "fname") 
      { 
       //Check your codes here 
      }    
     } 
+0

好的。我更新了代碼。 – 2015-02-11 05:49:11

+0

+1對於這一點,我現在可以得到FNAME的屬性的元素,但u能也告訴我的XPath表達式將匹配一個元素是否已經超過1個屬性。例如fname,lname,年齡 – jmc 2015-02-11 06:32:41

+0

@wintersolstice,您是否在XML中使用XMLDocument或Linq? – 2015-02-11 06:37:06

0
You can use enrollment/school/students/studentA/@fname 

@attribute是屬性選擇。

+0

Rohit的回答是正確的。我有一個錯字。它應該是招生/學校/學生/ studentA [@fname] – Sarathy 2015-02-11 06:01:03