2014-02-13 293 views
0

我想選擇在C#選擇節點使用XPath

使用XPath節點這是我的XML文件

<?xml version="1.0" encoding="utf-8"?> 
<xObject version="3.0.2002.0" xmlns="http://schemas.microsoft.com/wix/2006/objects"> 
    <section id="*" type="product"> 
     <table name="NotThis"> 
       <row sourceLineNumber="D:\bla\bla\"> 
        <field>Borderish.fo</field> 
        <field>Documents</field> 
        <field>1</field> 
        <field>No, not this line here 1</field> 
       </row> 
       <row sourceLineNumber="D:\blah\blah\"> 
        <field>Charterish</field> 
        <field>Documents</field> 
        <field>1</field> 
        <field>No not, this line here 2</field> 
       </row> 
      </table> 
     <table name="XFile"> 
      <row sourceLineNumber="D:\bla\bla\"> 
       <field>Borderish.fo</field> 
       <field>Documents</field> 
       <field>1</field> 
       <field>This line here 1</field> 
      </row> 
      <row sourceLineNumber="D:\blah\blah\"> 
       <field>Charterish</field> 
       <field>Documents</field> 
       <field>1</field> 
       <field>This line here 2</field> 
      </row> 
     </table> 
    </section> 
</xObject> 

這是我的C#代碼,這似乎行不通

XmlDocument doc = new XmlDocument(); 
     doc.Load("Testing.xml"); 
     XmlNode root = doc.DocumentElement; 

     XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
     nsmgr.AddNamespace("ns", "xmlns=&quot;http://schemas.microsoft.com/wix/2006/objects&quot;"); 

     XmlNodeList nodeList = root.SelectNodes("ns:table[@type='XFile']/ns:row", nsmgr); 

     foreach (XmlNode xn in nodeList) 
     { 
      string fieldLine = xn["Field"].InnerText; 
      Console.WriteLine("Field: {4}", fieldLine); 
     } 

我想要輸出的是每隔4個字段的表格名稱=「xfile」,像這樣:

This line here 1 

This line here 2 

如果您知道解決方案或更好的方法,請讓我知道。

回答

3

首先 - 你應該只是URI命名空間提供:

nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/wix/2006/objects"); 

二 - 提供節點名稱時,你應該使用的命名空間。而表有屬性name,而不是type

XmlNodeList nodeList = root.SelectNodes("//ns:table[@name='XFile']/ns:row", nsmgr); 

而在去年 - 選擇排節點後,你應該選擇第四場點(其中有姓名ns:field):

foreach (XmlNode row in nodeList) 
{ 
    XmlNode field = row.SelectSingleNode("(ns:field)[4]", nsmgr); 
    Console.WriteLine("Field: {0}", field.InnerText); 
} 

輸出:

Field: This line here 1 
Field: This line here 2 

注意:您可以直接獲取字段,而不必在行上循環:

XmlNodeList fields = 
    root.SelectNodes("//ns:table[@name='XFile']/ns:row/ns:field[4]", nsmgr);