Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - Converting an XML-document to a dictionary

I do not need to edit any XML-file or anything, this is only for reading and parsing.

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.

Is this possible? To treat the (parsed) XML-document as a dictionary?


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>

But if he requests y, it will be like

<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>"

Could be parsed and then accessed as doc["mengde"] etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...