如何读取xml节点标题及其值?

时间:2014-03-11 08:18:42

标签: c# asp.net xml

我关注xml并希望解析它并阅读每个node valuenode title。 我可以阅读value但无法阅读node title。我使用reader.Name但它总是返回empty string。我怎样才能读取节点标题?

string ExceptionDetails="<names><FirstName>John</FirstName><SecondName>White</SecondName></names>";
using (XmlReader reader = XmlReader.Create(new StringReader(ExceptionDetails)))
{
    while (reader.Read())
    {
       if (reader.NodeType == XmlNodeType.Element)
       {
          while (reader.Read())
          {
             if (reader.HasValue)
             {               
                sb.Append()+":"; //Read tag title
                sb.Append(reader.Value); sb.Append("<br/>");                      
             }
          }
       }
    }
}

结果:

FirstName:John
SecondName:white

2 个答案:

答案 0 :(得分:0)

   XDocument doc = XDocument.Load(Your XML);
    var elements = doc.Descendants( "names" );
    Dictionary<string, string> keyValues = new Dictionary<string, string>();
    for (int i = 0; i < elements.Count; i++)
    {
       string key = elements[i].Attributes["key"].Value.ToString();
       string value = elements[i].Attributes["value"].Value.ToString();
       keyValues.Add(key,value);
    }  

答案 1 :(得分:0)

您可以使用XmlReader.Name获取当前节点的名称。如果是元素,这是标记名称。为了记住文本之前的最后一个标记名称,在将它添加到StringBuilder之前,需要将它存储在变量中:

using System;
using System.Xml;
using System.IO;
using System.Text;

public class Test
{
    public static void Main()
    {
        StringBuilder sb = new StringBuilder();
        string ExceptionDetails="<names><FirstName>John</FirstName><SecondName>White</SecondName></names>";
        using (XmlReader reader = XmlReader.Create(new StringReader(ExceptionDetails)))
        {
            string tagName = string.Empty;
            while (reader.Read())
            {
               if (reader.NodeType == XmlNodeType.Element)
                   tagName = reader.Name;
               else if (reader.NodeType == XmlNodeType.Text)
               {               
                    sb.Append(tagName);
                    sb.Append(":"); //Read tag title
                    sb.Append(reader.Value); sb.Append("<br/>");                      
               }
            }
        }
        Console.WriteLine(sb.ToString());
    }
}

您可以运行示例here