java将xml转化为字典,将XML文档转换为字典

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:

foo

123

foobar

But if he requests y, it will be like

1000

...@...

foobar

The best would be if this:

100

3

foo

bar

bar

"

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

解决方案

You could use linq to xml to do what you want (if I understand what you want)

string data = "foofoobbbbb123foobar";

XDocument doc = XDocument.Parse(data);

Dictionary dataDictionary = new Dictionary();

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值