簡體   English   中英

如何在C#中解析具有多個xmlns屬性的xml?

[英]How to parse xml with multiple xmlns attribute in c#?

我有一個像上面一樣的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文檔,所有值都為null。 我認為這是因為Invoice標簽中有多個xmlns屬性。 我無法解決問題。

文檔的默認名稱空間是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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM