[英]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.