2012-04-12 47 views
1

XML值的一部分,我喜歡XML:獲得在C#

<RES> 
<MUL> 
    <SIN> 
    <KEY name="a"> 
    <VALUE>a1</VALUE> 
    </KEY> 
    <KEY name="b"> 
    <VALUE>b1</VALUE> 
    </KEY> 
    <KEY name="c"> 
    <VALUE>c1</VALUE> 
    </KEY> 
    <KEY name="need"> 
    <MUL> 
    <SIN> 
     <KEY name="needID"> 
     <VALUE>ID</VALUE> 
     </KEY> 
     <KEY name="needOther"> 
     <VALUE>other</VALUE> 
     </KEY> 
     <KEY name="needOther2"> 
     <VALUE>other2</VALUE> 
     </KEY> 
    </SIN> 
    </MUL> 
    </KEY> 
    </SIN> 
</MUL> 
</RES> 

我的問題是如何從與needID名稱節點獲得價值「身份證」?

我試着用

XmlDocument xx = new XmlDocument(); 
xx.Load(MYDOC); 

XmlNodeList node = xx.SelectNodes("/RES/MUL/SIN/KEY[@name='need']"); 

但在那之後,我不能挑needID與

XDocument doc = new XDocument(node); 
var cource = from x in doc.Descendants("KEY") 
select new { ID = doc.Element("VALUE").Value }; 

請幫幫我!

謝謝! :)

+0

我會考慮使用的XElement和後代() – 2012-04-12 11:50:42

回答

1

你需要的東西是這樣的:

// you're expecting only a single node - right?? So use .SelectSingleNode! 
XmlNode node = xx.SelectSingleNode("/RES/MUL/SIN/KEY[@name='need']"); 

// if we found the node... 
if(node != null) 
{ 
    // get "subnode" inside that node 
    XmlNode valueNode = node.SelectSingleNode("MUL/SIN/KEY[@name='needID']/VALUE"); 

    // if we found the <MUL>/<SIN>/<KEY name='needID'>/<VALUE> subnode.... 
    if(valueNode != null) 
    { 
     // get the inner text = the text of the XML element... 
     string value = valueNode.InnerText; 
    } 
} 

,或者你甚至可以認爲合併成一個單一的XPath操作,假設您知道最多隻有一個匹配的號碼去你的XML文檔中:

// define XPath 
string xpath = "/RES/MUL/SIN/KEY[@name='need']/MUL/SIN/KEY[@name='needID']/VALUE"; 

// you're expecting only a single node - right?? So use .SelectSingleNode! 
XmlNode node = xx.SelectSingleNode(xpath); 

// if we found the node... 
if(node != null) 
{ 
    // get the inner text = the text of the XML element... 
    string value = node.InnerText; 
} 
+0

謝謝!我會嘗試你的第一個解決方案,它適合我! – 2012-04-12 12:15:24

2

如何像下面

XDocument doc = XDocument.Load("url"); 

var cource = from x in doc.Descendants("KEY") 
       where x.Attribute("name").Value == "needID" 
       select new { ID = x.Element("VALUE").Value }; 

感謝

迪普

+0

在這裏,我得到異常: 「對象引用不設置到對象的實例」 ... – 2012-04-12 12:05:29

+0

的上面的代碼我粘貼了一個工作。我不知道爲什麼它不適合你。如果您將URL更改爲您的XML文件路徑,它應該可以工作。或者如果你有這個字符串XDocument doc = XDocument.Parse(MYDOC) – 2012-04-12 12:16:13

0
XmlDocument xml = new XmlDocument(); 

xml.Load(File.OpenRead(@"Your XML File")); 

//XmlNodeList xnList = xml.SelectNodes("/RES/MUL/SIN/KEY"); 

//You can use something like the below if the XML file is large and you need to read in more than one 
//foreach (XmlNode xn in xnList) 
//{ 
//Have a seperate class to store the values 
//class class = new class(); 
//class.ID = xn.SelectSingleNode("./@needID").Value; 
// 
//}