将XML文档转换为字典 [英] Converting an XML-document to a dictionary
问题描述
我不需要编辑任何XML文件或任何东西,这仅用于阅读和解析。
I do not need to edit any XML-file or anything, this is only for reading and parsing.
我希望能够将XML文档作为字典处理,如: username = doc [username];
,但是我找不到如何转换文档。我也遇到了重复键名的问题,但是可以通过将每个值添加为1,2等来轻松避免;这样可以很容易地循环使用。
I want to be able to handle the XML-document as a dictionary, like: username = doc["username"];
, but I can't find out how to "convert" the document. I've also encountered the problem with duplicate key-names, but that could be easlily avoided by appending each value with 1, 2 etc; making it easy to for-loop through too.
这可能吗?将(解析的)XML文档视为字典?
Is this possible? To treat the (parsed) XML-document as a dictionary?
Mehrdad的答案:
它不同于时间依赖于用户的请求。如果用户请求 x
,那么它将是:
Answer to Mehrdad:
It varies from time to time, it depends on the request from the user. If the user requests x
, then it will be:
<xml>
<test>foo</test>
<bar>123</bar>
<username>foobar</username>
</xml>
但是如果他要求 y
就像
<xml>
<ammount>1000</ammount>
<mail>...@...</mail>
<username>foobar</username>
</xml>
最好的是如果这样:
The best would be if this:
<xml>
<mengde>100</mengde>
<type>3</type>
<mail>foo</mail>
<crypt>bar</crypt>
<username>bar</username>
</xml>"
可以解析然后以 doc [mengde]
等。
推荐答案
你可以使用linq来xml你想要什么(如果我理解你想要的)
You could use linq to xml to do what you want (if I understand what you want)
string data = "<data><test>foo</test><test>foobbbbb</test><bar>123</bar><username>foobar</username></data>";
XDocument doc = XDocument.Parse(data);
Dictionary<string, string> dataDictionary = new Dictionary<string, string>();
foreach (XElement element in doc.Descendants().Where(p => p.HasElements == false)) {
int keyInt = 0;
string keyName = element.Name.LocalName;
while (dataDictionary.ContainsKey(keyName)) {
keyName = element.Name.LocalName + "_" + keyInt++;
}
dataDictionary.Add(keyName, element.Value);
}
这篇关于将XML文档转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!