[英]Parse a XDocument to a Dictionary<string, string>
我需要在正確的方向上推動如何將整個XML文檔解析為字典。 我的計划是將密鑰作為路徑,每個嵌套類型由“ - >”拆分。 例如:
<Foo>
<Bar>3</Bar>
<Foo>
<Bar>10</Bar>
</Foo>
</Foo>
如果我想獲得一個值,我只需使用以下方法將其從字典中刪除:
string value = Elements["Foo->Bar"];
我不確定如何遞歸地瀏覽每個元素。 任何幫助贊賞。
直截了當的解決方案:
private static string GetElementPath(XElement element)
{
var parent = element.Parent;
if(parent == null)
{
return element.Name.LocalName;
}
else
{
return GetElementPath(parent) + "->" + element.Name.LocalName;
}
}
static void Main(string[] args)
{
var xml = @"
<Foo>
<Bar>3</Bar>
<Foo>
<Bar>10</Bar>
</Foo>
</Foo>";
var xdoc = XDocument.Parse(xml);
var dictionary = new Dictionary<string, string>();
foreach(var element in xdoc.Descendants())
{
if(!element.HasElements)
{
var key = GetElementPath(element);
dictionary[key] = (string)element;
}
}
Console.WriteLine(dictionary["Foo->Bar"]);
}
你需要看一下xpath,所用路徑的格式與你想要的路徑有點不同,但是你可以創建一個wrap函數if neacacary
string GetByPath(string mypath)
{
//process path, and reformat it to xpath
//then get by xpath
}
http://support.microsoft.com/kb/308333
http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C
另一種選擇,但不確定XML文檔的真實結構
string data = "<Foo><Bar>3</Bar><Foo><bar>123</bar></Foo></Foo>";
XDocument xdoc = XDocument.Parse(data);
Dictionary<string, string> dataDict = new Dictionary<string, string>();
foreach (XElement xelement in doc.Descendants().Where(x => x.HasElements == false))
{
int keyInt = 0;
string keyName = xelement.Name.LocalName;
while (dataDict.ContainsKey(keyName))
keyName = xelement.Name.LocalName + "->" + keyInt++;
dataDict.Add(keyName, xelement.Value);
}
public static void parse()
{
Stack<String> stck = new Stack<string>();
List<String> nodes = new List<string>();
Dictionary<String, String> dictionary = new Dictionary<string, string>();
using (XmlReader reader = XmlReader.Create("path:\\xml.xml"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
stck.Push(reader.Name);
}
if (reader.NodeType == XmlNodeType.Text)
{
StringBuilder str = new StringBuilder();
if (stck.Count > 0)
nodes = stck.ToList<String>();
//List<String> _nodes ;
nodes.Reverse(0,nodes.Count);
foreach (String node in nodes)
str.Append(node + " --> ");
dictionary.Add(str.ToString(), reader.Value);
str.Clear();
}
if (reader.NodeType == XmlNodeType.EndElement)
{
stck.Pop();
}
}
}
foreach (KeyValuePair<String, String> KVPair in dictionary)
Console.WriteLine(KVPair.Key + " : " + KVPair.Value);
Console.Read();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.