【问题标题】:Get xml attribute with XDocument based on value of another xml attribute基于另一个 xml 属性的值,使用 XDocument 获取 xml 属性
【发布时间】:2016-05-21 02:03:22
【问题描述】:

我有一些看起来像这样的 xml:

<forms>
    <form name="admin" title="Admin Info">
        <field name="primary" label="Primary Name" required="false">
        <group desc="General" name="personalinfo" required="false" hide="false">
            <field label="Photos" name="photoupload" required="false" hide="false">
            <field label="First Name" name="firstanme" required="false" hide="false">
        </group>
    </form>
    <form name = "..." etc>
        ....etc...
    </form>
</forms>

我正在尝试从内部“字段”标签中获取信息。例如,我想在 name="photoupload" 时获取“required”和“hide”值。

到目前为止我所拥有的:

        XDocument doc = XDocument.Parse(xmlTemplate);
        var photoInfo = doc.Descendants("field")
                                .Where(field => field.Attribute("name").Value == "photoupload")
                                .Select(field => new
                                {
                                    Hide = field.Attribute("hide").Value,
                                    Required = field.Attribute("required").Value
                                })
                                .Single();

        photoInfoTextBox.Text = photoInfo.Hide.ToString();

但是,我收到“Object reference not set to an instance of an object.”错误。我的猜测是代码试图从第一个“字段”标签(其中 name="primary")中获取信息,但实际上我想要来自内部字段标签的信息,特别是:

forms/form(where name="admin")/group(where desc="general")/field(where name="photoupload")。

我该怎么做呢?

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    只需使用强制转换而不是读取Value 属性:

        var photoInfo = doc.Descendants("field")
                           .Where(field => (string)field.Attribute("name") == "photoupload")
                           .Select(field => new {
                                    Hide = (bool?)field.Attribute("hide"),
                                    Required = (bool?)field.Attribute("required")
                           })
                           .Single();
    

    您很可能有一个例外,因为某些field 元素没有name 属性。这意味着field.Attribute("name") 将返回null。而null.Value 将抛出NullReferenceException。请注意,有些元素也没有hide 属性。

    当您将XAttributeXElement 转换为可以具有null 值的类型时,如果属性或元素不存在,您将得到null。不会抛出异常。

    注意:因此您只有一个具有给定名称的field,您可以简单地尝试获取该字段

    var photoUpload = doc.Descendants("field")
                         .Single(f => (string)f.Attribute("name") == "photoupload");
    
    // or
    var photoUpload = doc.XPathSelectElement("//field[@name='photoupload']");
    

    【讨论】:

    • 哇,谢谢!我在尝试使用铸造的第一部分时仍然遇到问题。但是,您是对的,我需要的字段具有唯一名称,因此我可以使用您的方法直接获取它。然后我可以使用 var isRequired = photoupload.Attribute("required");谢谢!
    • @Rohhan 如果文档中可能没有具有给定名称的字段,那么您可以使用SingleOrDefault 而不是Single,并在读取其他属性值之前检查结果是否为null
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多