【发布时间】: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