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

时间:2021-01-20 18:55:10

Here's the XML string.

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

So how could I get value of <response> element by given question Id? Say, if I give id value = "dd7e3bce-57ee-497a-afe8-e3d8d25e2671", I'd like to have string value abcdefg returned as result.

那么如何通过给定的问题Id获得 元素的值呢?例如,如果我输入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 个解决方案

#1


12  

you might need to do like this , problem i think is reader is not moving to text and because of that you are getting empty

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

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

Above one is working for me you can try out at your end

以上是我的工作,你可以在你那边试试

#2


5  

I would use LINQ2XML..

我会用LINQ2XML . .

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

#3


1  

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

//it works for me !!!!

//它对我有用!

#4


0  

You can use this function to get response for specific questionID from xml stored in QuestionXML.xml.

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

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;
            }

#1


12  

you might need to do like this , problem i think is reader is not moving to text and because of that you are getting empty

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

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

Above one is working for me you can try out at your end

以上是我的工作,你可以在你那边试试

#2


5  

I would use LINQ2XML..

我会用LINQ2XML . .

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

#3


1  

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

//it works for me !!!!

//它对我有用!

#4


0  

You can use this function to get response for specific questionID from xml stored in QuestionXML.xml.

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

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;
            }