c# – 使用XmlSerializer的多个名称空间
发布时间:2020-12-15 21:26:22 所属栏目:百科 来源:网络整理
导读:这是场景: 我有嵌套类,需要在xml文档中序列化 [XmlRoot(Namespace="http://www.foo.bar/myschema")]public class root { [XmlAttribute] public string version { get; set; } [XmlElement] public child child { get; set; } ...}[XmlRoot(Namespace="http
这是场景:
我有嵌套类,需要在xml文档中序列化 [XmlRoot(Namespace="http://www.foo.bar/myschema")] public class root { [XmlAttribute] public string version { get; set; } [XmlElement] public child child { get; set; } ... } [XmlRoot(Namespace="http://www.foo.bar/myschema")] public class child { [XmlElement] public int elemA { get; set; } [XmlElement] public string elemB { get; set; } ... } 我已经创建了一个基于另一个示例的方法来删除其他名称空间并设置自定义名称空间: public static void Save<T>(this T type,string path) { System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type.GetType()); System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("","http://www.foo.bar/myschema"); using(XmlWriter file = XmlWriter.Create(path)) { xs.Serialize(file,type,ns); } } 我得到这个代码的结果: <?xml version="1.0" encoding="utf-8"?> <root xmlns="http://www.foo.bar/myschema" version="2.00"> <child> <elemA>1</elemA> ... </child> </root> 但期望这样: <?xml version="1.0" encoding="utf-8"?> <root xmlns="http://www.foo.bar/myschema" version="2.00"> <child xmlns="http://www.foo.bar/myschema"> <elemA>1</elemA> ... </child> </root> 我们必须在两个标记中设置自定义命名空间声明.这可能吗? 编辑: 这是一个现实世界的例子: <?xml version="1.0" encoding="UTF-8"?> <enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.01"> <idLote>200602220000001</idLote> <NFe xmlns="http://www.portalfiscal.inf.br/nfe"> <infNFe Id="NFe31060243816719000108550000000010001234567890" versao="1.01"> ... <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> ... </NFe> <NFe xmlns="http://www.portalfiscal.inf.br/nfe"> <infNFe Id="NFe31060243816719000108550000000010011234567900" versao="1.01"> ... <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> ... </NFe> <NFe xmlns="http://www.portalfiscal.inf.br/nfe"> <infNFe Id="NFe31060243816719000108550000000010021234567916" versao="1.01"> ... <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> ... </NFe> </enviNFe> 解决方法
从XML的角度来看,您的示例是相同的,因此第一个示例完全没问题.如果必须使用第二个,那么我们的XML理解或处理管道存在严重问题.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |