2012-04-12 43 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; 
// 
//}