2012-04-12 6 views
1

でXML-値の一部を取得しますか?私のようなXMLを持つC#の

は私が

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

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

てみましたが、その後、私は、私を助けてください

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

でneedIDを選ぶことはできません!

ありがとうございます!

// 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; 
    } 
} 

またはあなたが1つでもにそれを組み合わせることができ:

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

私はXElementオブジェクトと子孫を(使用を検討したい) –

答えて

1

以下のようなものについてはあなたがこのような何かを必要とするどのように:)

+0

ありがとう!私はあなたの最初のソリューションを試してみて、それは私の仕事です! –

2

XPath操作では、最大で1つの一致しないデあなたの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

ここで私は例外を受け取る: 「オブジェクトのインスタンスに設定されていないオブジェクト参照」... –

+0

上記のコード1は貼り付けられていました。私はなぜそれがあなたのために働いているのか分からない。 URLをXMLファイルのパスに変更すると、うまくいくはずです。またはこれを文字列として持つ場合XDocument doc = XDocument.Parse(MYDOC) –

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; 
// 
//} 
関連する問題