如何使用c#.net读取XML中的XML节点

时间:2010-06-01 06:42:31

标签: c# asp.net xml

我有一个XML文件,如下所示:

<report timestamp="3201" reportVersion="2" request="3981135340">
<question timedOut="false" time="3163" attempts="2" correct="true" id="13"> 
<answer status="attempt"> 
<radioButton correct="false" value="true" id="17" /> 
</answer> 
<answer status="correct"> 
<radioButton correct="true" value="true" id="15" /> 
</answer> 
</question> 
</report>

我想根据'answer'节点的'status'属性读取子节点。

4 个答案:

答案 0 :(得分:4)

使用XmlReader(最快但仅向前),XDocument(LINQ to XML)或XmlDocument。请参阅msdn文档中的示例。

答案 1 :(得分:1)

使用LINQ to XML:

using System.Xml.Linq;

var doc = XDocument.Parse(xml); // or XDocument.Load()
var elements = from e in doc.Descendants("answer")
               where e.Attribute("status").Value == "attempt"
               select e;

// elements will be IEnumerable<XElement>

答案 2 :(得分:0)

使用XmlDocument和XPath:

XmlDocument document = new XmlDocument();
//here you should load your xml for example with document.Load();
XmlNodeList nodes = document.SelectNodes("/report/question/answer[@status = 'correct']/radioButton");

只需根据需要修改XPath。

答案 3 :(得分:0)

尝试这个..

foreach (XmlNode xnode in xdoc.SelectNodes("report/question/answer"))
    {
        if (xnode.Attributes.GetNamedItem("status").Value == "correct")
        {
            string value = xdoc.SelectSingleNode("report/question/answer[@status='correct']/radioButton").Attributes.GetNamedItem("id").Value;

        }
        if (xnode.Attributes.GetNamedItem("status").Value == "attempt")
        {
            string value = xdoc.SelectSingleNode("report/question/answer[@status='attempt']/radioButton").Attributes.GetNamedItem("id").Value;
        }
    }