本文介绍了如何使用XmlReader从XML中的特定子元素获取价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是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 作为结果.

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.

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

推荐答案

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

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

这篇关于如何使用XmlReader从XML中的特定子元素获取价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 23:15