我有一个类似上面的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文档,所有值都为空。我认为这是因为发票标签中有多个xmlns属性。我解决不了这个问题。
发布于 2019-05-24 04:51:29
文档的默认名称空间是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中,如果您有疑问,可以使用Edit > Paste Special > Paste Xml As Classes来查看如何装饰一个类来匹配您的XML。
https://stackoverflow.com/questions/56281998
复制相似问题