如何使用XmlReader从XML中的特定子元素获取值?

时间:2013-09-19 09:37:42

标签: c# .net xml xmlreader

这是XML字符串。

<?xml version="1.0" encoding="utf-16"?>
<questionresponses>
  <question id="dd7e3bce-57ee-497a-afe8-e3d8d25e2671">
    <text>Question 1?</text>
    <response>abcdefg</response>
    <correctresponse>123</correctresponse>
  </question>
  <question id="efc43b1d-048f-4ba9-9cc0-1cc09a7eeaf2">
    <text>Question 2?</text>
    <response>12345678</response>
    <correctresponse>123</correctresponse>
  </question>
</questionresponses>

那么如何通过给定的问题ID获得<response>元素的值?比方说,如果我给id值=“dd7e3bce-57ee-497a-afe8-e3d8d25e2671”,我希望结果返回字符串值abcdefg

var xmlstr = "content from above xml example";
using (var reader = XmlReader.Create(new StringReader(xmlstr)))
{
    while(reader.Read())
    {
        if(reader.IsStartElement())
        {
            var attr = reader["id"];
            if(attr != null && attr == "dd7e3bce-57ee-497a-afe8-e3d8d25e2671")
            {
                if(reader.ReadToDescendant("response"))
                {
                    result = reader.Value; // <= getting empty string? So what's wrong?
                    break;
                }
            }
        }
    }
}

4 个答案:

答案 0 :(得分:16)

你可能需要这样做,我认为问题是读者没有移动到文本,因为你变得空虚

        if(reader.ReadToDescendant("response"))
            {
                reader.Read();//this moves reader to next node which is text 
                result = reader.Value; //this might give value than 
                break;
            }

一个人正在为我工​​作,你可以尝试一下

答案 1 :(得分:5)

我会使用LINQ2XML ..

XDocument doc=XDocument.Parse(xmlstr);
String response=doc.Elements("question")
                   .Where(x=>x.Attribute("id")==id)
                   .Single()
                   .Element("response")
                   .Value;

答案 2 :(得分:1)

if (reader.NodeType == XmlNodeType.Element)
{
    if(reader.Name == "response")
    {
        reader.read();
        var res = reader.Value;
    }
} 

//它对我有用!!!!

答案 3 :(得分:0)

您可以使用此功能从存储在 QuestionXML.xml 中的xml获取特定questionID的响应。

private string getResponse(string questionID)
            {
                string response = string.Empty;
                using (StreamReader sr = new StreamReader("QuestionXML.xml", true))
                {
                    XmlDocument xmlDoc1 = new XmlDocument();
                    xmlDoc1.Load(sr);
                    XmlNodeList itemNodes = xmlDoc1.GetElementsByTagName("question");
                    if (itemNodes.Count > 0)
                    {
                        foreach (XmlElement node in itemNodes)
                        {
                            if (node.Attributes["id"].Value.ToString() == questionID.Trim())
                            {
                                response = node.SelectSingleNode("response").InnerText;
                                break;
                            }

                        }
                    }
                }
                return response;
            }