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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18891207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:31:48  来源:igfitidea点击:

How to get value from a specific child element in XML using XmlReader?

c#.netxmlxmlreader

提问by woodykiddy

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 abcdefgreturned as result.

那么如何<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;
                }
            }
        }
    }
}

采纳答案by Pranay Rana

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

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

回答by Anirudha

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;

回答by Rezoan

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

您可以使用此函数从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;
            }

回答by gustavo ortega

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

//it works for me !!!!

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