[英]Get part of XML-value in C#
I have XML like: 我有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>
My question is how to get value 'id' from the node with the name of needID
? 我的问题是如何从名为needID
的节点获取值'id'?
I tried with 我试过了
XmlDocument xx = new XmlDocument();
xx.Load(MYDOC);
XmlNodeList node = xx.SelectNodes("/RES/MUL/SIN/KEY[@name='need']");
but after that I can't pick needID with 但之后我不能选择needID了
XDocument doc = new XDocument(node);
var cource = from x in doc.Descendants("KEY")
select new { ID = doc.Element("VALUE").Value };
Please, help me! 请帮我!
Thanks! 谢谢! :) :)
How about something like below 怎么样下面的东西
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 };
Thanks 谢谢
Deepu 迪普
You need something like this: 你需要这样的东西:
// 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;
}
}
or you could even combine that into a single XPath operation, assuming you know that you have at most one single matching node in your XML document: 或者您甚至可以将它组合到单个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;
//
//}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.