我关注xml
并希望解析它并阅读每个node value
和node 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
答案 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。