如何摆脱xelement的麻烦? [英] How to get a tablerow out of an xelement?

查看:85
本文介绍了如何摆脱xelement的麻烦?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个元素:

<adress name="company1" street="street1" City="city1" <branch key="1" value="branch1" /><language key="1" value="langauge1" /> </adress>

如您所见,元素地址中有几个属性,它继承了元素分支和语言,

as you see there are several attributes in the element adress and it inherits the elements branch and language which also containing some attributes.

我想要一个这样的表:

name street city branchvalue branchkey languagevalue languagekey

我该怎么做?我可以对其进行硬编码,因为xml方案每次都是一样的,但是,我希望有一个动态而苗条的解决方案

How can I do this? I can hardcode it, because the xml scheme is everytime the same but, i would like to have a dynamic and slim solution

推荐答案

这是一种实现方法的示例。您确实应该进行空检查,而不是假设所有属性都存在值,但是如果您可以信任它,就可以这样做:

Here's an example of one way to do it. You really should do null checking and not assume all attributes are present with values, but if you can trust it, here you go:

    string strElem = "<adress name=\"company1\" street=\"street1\" City=\"city1\"><branch key=\"1\" value=\"branch1\" /><language key=\"1\" value=\"langauge1\" /> </adress>";
    XElement xel = XElement.Parse(strElem);

    var branch = xel.Element("branch");
    var lang = xel.Element("language");

    var theTable = new {
        name = xel.Attribute("name").Value, 
        street = xel.Attribute("street").Value, 
        city = xel.Attribute("City").Value,
        branchkey = branch.Attribute("key").Value,
        branchvalue = branch.Attribute("value").Value,
        languagevalue = lang.Attribute("key").Value,
        languagekey = lang.Attribute("value").Value
        };




Update

Update

根据新的证据...
我仍​​然不确定这是否适合您的需求,但是您可以动态创建字典。从那里,您可以对数据进行任何操作:

In light of new evidence... I'm still not sure if this suits your needs, but you can dynamically create a Dictionary. From there you can do whatever you want with the data:

            string strElem = "<adress name=\"company1\" street=\"street1\" City=\"city1\"><branch key=\"1\" value=\"branch1\" /><language key=\"1\" value=\"langauge1\" /> </adress>";
            XElement xel = XElement.Parse(strElem);

            var theTable = new ExpandoObject() as IDictionary<string, Object>;
            foreach (XAttribute attr in xel.Attributes())
            {
                theTable.Add(attr.Name.LocalName, attr.Value);
            }

            foreach (XElement el in xel.Elements())
            {
                foreach (XAttribute attr in el.Attributes())
                {
                    theTable.Add(el.Name + attr.Name.LocalName, attr.Value);
                }
            }

这篇关于如何摆脱xelement的麻烦?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆