[英]Serialize object to XML with xmlns attribute only, without prefix
[英]How to serialize an object to XML without getting xmlns=“…”?
有沒有辦法讓我在 .NET 中序列化一個對象,而沒有 XML 命名空間也自動序列化? 似乎默認情況下 .NET 認為應該包含 XSI 和 XSD 命名空間,但我不希望它們存在。
啊……沒關系。 總是在提出問題后進行搜索才能得出答案。 我正在序列化的對象是obj
並且已經定義。 將帶有單個空命名空間的 XMLSerializerNamespace 添加到集合中即可。
在 VB 中是這樣的:
Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")
Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True
Using ms As New MemoryStream(), _
sw As XmlWriter = XmlWriter.Create(ms, settings), _
sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using
在 C# 中是這樣的:
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);
如果你想擺脫額外的xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
和xmlns:xsd="http://www.w3.org/2001/XMLSchema"
,但仍然保留您自己的命名空間xmlns="http://schemas.YourCompany.com/YourSchema/"
,除了這個簡單的更改外,您使用與上面相同的代碼:
// Add lib namespace with empty prefix
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");
如果您想刪除命名空間,您可能還想刪除版本,為了節省您的搜索時間,我添加了該功能,因此下面的代碼將同時執行這兩項操作。
我還用通用方法將它包裝起來,因為我正在創建非常大的 xml 文件,這些文件太大而無法在內存中進行序列化,因此我將輸出文件分解並將其序列化為較小的“塊”:
public static string XmlSerialize<T>(T entity) where T : class
{
// removes version
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
using (StringWriter sw = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
// removes namespace
var xmlns = new XmlSerializerNamespaces();
xmlns.Add(string.Empty, string.Empty);
xsSubmit.Serialize(writer, entity, xmlns);
return sw.ToString(); // Your XML
}
}
我建議這個助手類:
public static class Xml
{
#region Fields
private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};
private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName("", "")});
#endregion
#region Methods
public static string Serialize(object obj)
{
if (obj == null)
{
return null;
}
return DoSerialize(obj);
}
private static string DoSerialize(object obj)
{
using (var ms = new MemoryStream())
using (var writer = XmlWriter.Create(ms, WriterSettings))
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(writer, obj, Namespaces);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
public static T Deserialize<T>(string data)
where T : class
{
if (string.IsNullOrEmpty(data))
{
return null;
}
return DoDeserialize<T>(data);
}
private static T DoDeserialize<T>(string data) where T : class
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
var serializer = new XmlSerializer(typeof (T));
return (T) serializer.Deserialize(ms);
}
}
#endregion
}
:)
如果您無法擺脫每個元素的額外 xmlns 屬性,則在從生成的類序列化為 xml 時(例如:使用xsd.exe時),您將獲得類似以下內容:
<manyElementWith xmlns="urn:names:specification:schema:xsd:one" />
然后我會與你分享對我有用的東西(以前的答案和我在這里找到的東西的混合)
顯式設置所有不同的 xmlns 如下:
Dim xmlns = New XmlSerializerNamespaces()
xmlns.Add("one", "urn:names:specification:schema:xsd:one")
xmlns.Add("two", "urn:names:specification:schema:xsd:two")
xmlns.Add("three", "urn:names:specification:schema:xsd:three")
然后將其傳遞給序列化
serializer.Serialize(writer, object, xmlns);
您將在根元素中聲明三個命名空間,並且不再需要在其他元素中生成相應的前綴
<root xmlns:one="urn:names:specification:schema:xsd:one" ... />
<one:Element />
<two:ElementFromAnotherNameSpace /> ...
XmlWriterSettings settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
StringBuilder sb = new StringBuilder();
XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));
using (XmlWriter xw = XmlWriter.Create(sb, settings))
{
xs.Serialize(xw, model, ns);
xw.Flush();
return sb.ToString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.