2011-06-22 50 views
20

我有一個遇到XML文檔(使用C#)的問題並獲取所有必需的值。我成功地遍歷了XML文檔中的所有指定的XmlNodeLists,成功獲取了所有的XmlNode值,但是我必須在這個XmlNodeList之外獲得一些值。從XML文檔獲取指定的節點值

例如:

<?xml version="1.0" encoding="UTF-8" ?> 
<Element xsi:schemaLocation="http://localhost/AML/CaseInvestigationMangement/Moduli/XmlImportControls/xsdBorrow.xsd xsd2009027_kor21.xsd" Kod="370" xmlns="http://localhost/AML/CaseInvestigationMangement/Moduli/XmlImportControls/xsdBorrow.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
/2001/XMLSchema-instance"> 
    <ANode> 
     <BNode> 
      <CNode> 
       <Example> 
        <Name>John</Name> 
        <NO>001</NO> 
       </Example> 
      </CNode> 
     </BNode> 
     <ID>1234</ID> 
     <Date>2011-10-01</Date> 
    </ANode> 
    <ANode> 
     <BNode> 
      <CNode> 
       <Example> 
        <Name>Mike</Name> 
        <NO>002</NO> 
       </Example> 
      </CNode> 
     </BNode> 
     <ID>5678</ID> 
     <Date>2011-03-31</Date> 
    </ANode> 
</Element> 

這是得到的節點名稱值的代碼和NO在每一個XML文檔中發現的陽極:

XmlDocument xml = new XmlDocument(); 
xml.LoadXml(myXmlString); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString(); 
XmlNodeList xnList = xml.SelectNodes("/Element[@*]/ANode/BNode/CNode"); 
foreach (XmlNode xn in xnList) 
{ 
    XmlNode example = xn.SelectSingleNode("Example"); 
    if (example != null) 
    { 
     string na = example["Name"].InnerText; 
     string no = example["NO"].InnerText; 
    } 
} 

現在我有獲取值的問題ID和日期。

回答

24

就像你從得到的東西做CNode你還需要爲ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]"); 
foreach (XmlNode xn in xnList) 
{ 
    XmlNode anode = xn.SelectSingleNode("ANode"); 
    if (anode!= null) 
    { 
     string id = anode["ID"].InnerText; 
     string date = anode["Date"].InnerText; 
     XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode"); 
     foreach (XmlNode node in CNodes) 
     { 
     XmlNode example = node.SelectSingleNode("Example"); 
     if (example != null) 
     { 
      string na = example["Name"].InnerText; 
      string no = example["NO"].InnerText; 
     } 
     } 
    } 
} 
+0

我嘗試這樣做,但我沒有得到任何價值。 「陽極」爲空,並跳到一行:「if(陽極!=空)」。 –

+0

也嘗試從第一行刪除**陽極**。第一行應該是'XmlNodeList xnList = xml.SelectNodes(「/ Element [@ *]」);'。在這種情況下,我得到了** id **和** date **的值,但是我在foreach(CNodes中的XmlNode節點)行中得到了跳轉。 –

+0

立即嘗試。編輯的版本應該可以工作。 – msarchet