![](/img/trans.png)
[英]How to custom serialise json with .net core and JsonSerializer
[英]How to serialise with custom namespace
我将一个对象序列化为XML,并得到如下输出:
<?xml version="1.0" encoding="utf-8"?>
<SOrd xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
但是我希望这样:
<SOrd xmlns:SOrd="http://..." xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://....xsd">
我怎样才能做到这一点?
我试过在序列化之前将属性添加到根对象中,这也是:
XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("xmlns:SOrd", "http://...");
xmlNameSpace.Add("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNameSpace.Add("xsi:schemaLocation", "http://....xsd");
XmlSerializer xs = new XmlSerializer(ord.GetType());
TextWriter writer = new StreamWriter(outputPath, false);
xs.Serialize(writer, ord, xmlNameSpace);
writer.Close();
但是我得到一个异常“名称中不能包含':'字符,十六进制值0x3A”。
首选项不能包含“:”,取出第一部分xmlns:
这是您的代码略微更改的:
XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("SOrd", "http://...");
xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNameSpace.Add("schemaLocation", "http://....xsd");
XmlSerializer xs = new XmlSerializer(ord.GetType());
TextWriter writer = new StreamWriter(outputPath, false);
xs.Serialize(writer, ord, xmlNameSpace);
writer.Close();
请确保为每个类添加必需的属性,因为不包含序列化属性。 有关属性继承的更多信息,请参见: 如何反序列化XML抽象类的具体实现
编辑
您可以这样实现xsi:shcemaLocation:
[XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar", DataType = "schemaLocation")]
public class Foo
{
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string schemaLocation = "http://example";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.