【问题标题】:Serialize object to XML with xmlns attribute only, without prefix仅使用 xmlns 属性将对象序列化为 XML,不带前缀
【发布时间】:2021-06-10 14:27:30
【问题描述】:

我需要序列化我的 Root 对象:

public class Root{
    [XmlElement(ElementName = "docs", Namespace = "http://example.com/osoz-edi")]
    public Documents Documents{get;set;}
}
[XmlRoot(ElementName = "docs")]
public class Documents {
    [XmlElement(ElementName = "invoice", Namespace = "")]
    public Invoice Invoice{get;set;}
}
[XmlRoot(ElementName = "invoice", Namespace = "")]
public class Invoice {
    [XmlElement(ElementName = "id", Namespace = "")]
    public string Id{get;set;}
    [XmlElement(ElementName = "number", Namespace = "")]
    public string Number{get;set;}
}

像这样的 XML:

<Root xmlns:ksx="http://example.com/osoz-edi">
    <docs xmlsns="http://example.com/osoz-edi">
        <invoice>
            <id>1</id>
            <number>222</number>
        </invoice>
    </docs>
</Root>

但是我得到了这样的东西:

<Root xmlns:ksx="http://example.com/osoz-edi">
    <ksx:docs>
        <invoice>
            <id>1</id>
            <number>222</number>
        </invoice>
    </ksx:docs>
</Root>

我正在使用这个进行序列化:


var root = new Root(); 
.... //filling object with data
using (var sww = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sww))
{   
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 
    ns.Add("ksx", "http://example.com/osoz-edi");   
    XmlSerializer xsSubmit = new XmlSerializer(typeof(Stylesheet));
    xsSubmit.Serialize(writer, root, ns);   
}

当我在不传递 XmlSerializerNamespaces 的情况下进行序列化时,我会得到这样的 XML:

<Root>
    <docs xmlns="http://example.com/osoz-edi">
        <invoice>
            <id>1</id>
            <number>222</number>
        </invoice>
    </docs>
</Root>

如何在根元素中获取命名空间,在文档元素中获取属性?

【问题讨论】:

  • xmlsns?是不是打错字了?
  • 在您的“to XML like this”示例中,您实际上并没有在任何地方使用ksx 命名空间?
  • 从信息的角度来看,您尝试创建的结果(使用完全未使用的 XML 命名空间 ksx)没有意义。
  • 来自:XmlSerializer xsSubmit = new XmlSerializer(typeof(Stylesheet)); To : XmlSerializer xsSubmit = new XmlSerializer(typeof(Root));
  • xmlsns - 是的,错字了,应该是 xmlns

标签: c# .net xml


【解决方案1】:

您的 Root 类缺少 XmlRoot 属性:

[XmlRoot(ElementName = "Root", Namespace = "http://example.com/osoz-edi"]
public class Root
{
    // ...
}

另外,您的其他两个类不需要 XmlRoot 属性。

XmlElementAttribute 表示“此字段或属性表示一个子元素”; XmlRootAttribute 表示“这是 XML 文档根元素的一种潜在格式”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2011-12-20
    • 2015-02-06
    相关资源
    最近更新 更多