在 C# 中获取 XML 值的一部分

本文关键字:一部分 XML 获取 | 更新日期: 2023-09-27 18:30:48

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

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

我试过

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

求你,帮帮我!

谢谢! :)

在 C# 中获取 XML 值的一部分

下面

这样的东西怎么样

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

谢谢

迪普

你需要这样的东西:

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