1

我有像这样的XML:

<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>

我的问题是如何从名称为的节点获取值“id” needID

我试过了

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

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

但在那之后我不能选择需要ID

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

请帮我!

谢谢!:)

4

3 回答 3

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

谢谢

迪普

于 2012-04-12T11:46:24.663 回答
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;
}
于 2012-04-12T11:52:45.940 回答
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;
//
//}
于 2012-04-12T11:57:36.863 回答