[英]Serialize object to XML with xmlns attribute only, without prefix
我需要序列化我的根 object:
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>
如何在根元素中获取命名空间,并在 docs 元素中获取属性?
您的 Root class 缺少 XmlRoot 属性:
[XmlRoot(ElementName = "Root", Namespace = "http://example.com/osoz-edi"]
public class Root
{
// ...
}
此外,您的其他两个类不需要 XmlRoot 属性。
XmlElementAttribute 说“这个字段或属性代表一个子元素”; XmlRootAttribute 说“这是 XML 文档的根元素的潜在格式”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.