[英]Parse generic XML string using C#
假設我有以下XML字符串:
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item1>value1</item1>
<item2>value2</item2>
<item3>value3</item3>
<item4>value4</item4>
<item5>value5</item5>
<item6>value6</item6>
</items>
我需要以通用的方式解析它,因為它可能會在以后更新,我不需要相應地修改我的代碼。 所以我嘗試了以下方法:
public static Dictionary<string, string> Parser(string xmlString)
{
Dictionary<string, string> parserDictionary = new Dictionary<string, string>();
using (StringReader stringReader = new StringReader(xmlString))
using (XmlTextReader reader = new XmlTextReader(stringReader))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
parserDictionary.Add(reader.Name, reader.ReadString());
break;
}
}
}
return parserDictionary;
}
此代碼有2個問題:
<items>
元素,我不需要解析它 <item1>
請指教
為什么不是這樣的:
var parserDictionary = XDocument.Create(xmlString)
.Descendants("items")
.Elements()
.Select(elem => new { Name = elem.Name.LocalName, Value = elem.Value })
.ToDictionary(k => k.Name, v => v.Value);
你甚至可以這樣做:
var parserDictionary = XDocument.Create(xmlString)
.Descendants("items")
.Elements()
.ToDictionary(k => k.Name.LocalName, v => v.Value);
如果您需要將XML轉換為對象表示而不是簡單易用
XDocument xDoc = XDocument.Parse(xmlString);
這真的是你需要做的。 完成后,您可以使用Elements
, Element
, Attribute
, Attributes
和Descendants
屬性查詢xDoc
。
例如,這里有一些代碼可以打印所有值
XDocument xDoc = XDocument.Parse(xmlString);
foreach(XElement e in xDoc.Elements())
{
Console.WriteLine(e.Value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.