【问题标题】:How to parse xml with multiple xmlns attribute in c#?如何在 C# 中解析具有多个 xmlns 属性的 xml?
【发布时间】:2019-05-23 19:45:01
【问题描述】:

我有一个像上面这样开头的xml

<Invoice 
    xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2../xsdrt/maindoc/UBL-Invoice-2.1.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xades="http://uri.etsi.org/01903/v1.3.2#"
    xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"
    xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
    xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
    xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" 
    xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2">

        <cbc:UBLVersionID>2.1</cbc:UBLVersionID>
        <cbc:CustomizationID>TR1.2</cbc:CustomizationID>
        <cbc:ProfileID>TEMELFATURA</cbc:ProfileID>
        <cbc:ID>ALP2018000007216</cbc:ID>

        <!-- ... -->

我尝试用这样的方法解析 xml

public static T FromXml<T>(string xmlString)
{
    StringReader xmlReader = new StringReader(xmlString);
    XmlSerializer deserializer = new XmlSerializer(typeof(T));

    return (T)deserializer.Deserialize(xmlReader);
}

我的xml模型和上面一样

[Serializable]
[XmlRoot(
    Namespace = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2", 
    ElementName = "Invoice", 
    DataType = "string", 
    IsNullable = true)]
public class Invoice
{
    public string CustomizationID { get; set; }
    // ...
}

但是,我无法解析 xml 文档,所有值都为空。我认为这是因为 Invoice 标签中有多个 xmlns 属性。我无法解决问题。

【问题讨论】:

    标签: c# xml parsing


    【解决方案1】:

    文档的默认命名空间为urn:oasis:names:specification:ubl:schema:xsd:Invoice-2,您已正确放入XmlRoot,但UBLVersionID 等子元素以cbc 为前缀,这是一个不同的命名空间。您必须将该命名空间放在属性上,让序列化程序知道它是什么。

    例如:

    [Serializable]
    [XmlRoot(
        Namespace = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
        ElementName = "Invoice",
        DataType = "string",
        IsNullable = true)]
    public class Invoice
    {
        [XmlElement(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
        public string CustomizationID { get; set; }
        // ...
    }
    

    在 Visual Studio 中,如果您有疑问,可以使用编辑 > 选择性粘贴 > 将 Xml 粘贴为类来查看如何装饰类以匹配您的 XML。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 2017-09-14
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多