9

这是 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>

那么如何<response>通过给定的问题 ID 获取元素的值?说,如果我给 id value = "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

4 回答 4

22

你可能需要这样做,我认为问题是阅读器没有转向文本,因此你变得空虚

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

以上一个对我有用,你可以在你的最后尝试

于 2013-09-19T09:51:34.050 回答
5

我会使用 LINQ2XML ..

XDocument doc=XDocument.Parse(xmlstr);
String response=doc.Elements("question")
                   .Where(x=>x.Attribute("id")==id)
                   .Single()
                   .Element("response")
                   .Value;
于 2013-09-19T09:55:38.663 回答
1
if (reader.NodeType == XmlNodeType.Element)
{
    if(reader.Name == "response")
    {
        reader.read();
        var res = reader.Value;
    }
} 

//这个对我有用 !!!!

于 2015-07-01T18:43:25.950 回答
0

您可以使用此函数从存储在QuestionXML.xml中的 XML 中获取特定问题的响应。

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;
            }
于 2013-09-19T12:18:51.943 回答