Ger*_*ero 1 c# xml-serialization xmlserializer
我有一个对象,我想序列化它。我想将命名空间添加到 xml 文档的特定元素。我从 1 个默认 xml 创建了多个 .xsd 文件。我使用 XmlSerializer。
命名空间应该在<sos:element. 这就是我想要的:
<env:root
xmls:env ="httpenv"
xmlns:sos="httpsos">
<env:body>
<sos:element
xmlns:abc="" <--------------my namespaces are located in <sos:element
...
Run Code Online (Sandbox Code Playgroud)
如果我使用类似的东西
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("abc", "httpabc");
ns.add....
StringWriter stringWriter = new StringWriter();
serializer.Serialize(stringWriter, ObjectToSerialize, ns);
Run Code Online (Sandbox Code Playgroud)
我将得到以下内容
<env:root
xmls:env ="httpenv"
xmlns:sos="httpsos"
xmlns:abc="" <-------------I do not want it here; I want it in <sos:element
<env:body>
<sos:element>
...
Run Code Online (Sandbox Code Playgroud)
有没有办法指定我想要在哪里(在哪个元素中)声明我的命名空间,或者它们都在根元素中声明?
从 XML 的角度来看,XML 命名空间在哪里定义并不重要。如果您需要在特定位置声明 XML 命名空间,则解析 XML 的组件可能存在问题。
好吧,无论如何,这就是我想出的:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace XMLNamespaceChangeSerialization
{
internal class Program
{
private static void Main(string[] args)
{
var serialize = Serialize();
Console.WriteLine(serialize);
Console.ReadLine();
}
private static string Serialize()
{
var ns = new XmlSerializerNamespaces();
ns.Add("env", "httpenv");
// Don't add it here, otherwise it will be defined at the root element
// ns.Add("sos", "httpsos");
var stringWriter = new StringWriter();
var serializer = new XmlSerializer(typeof (RootClass), "httpenv");
serializer.Serialize(stringWriter, new RootClass(), ns);
return stringWriter.ToString();
}
}
[Serializable]
[XmlRoot(ElementName = "root")]
public class RootClass
{
[XmlElement(ElementName = "body", Namespace = "httpenv")]
public BodyClass body = new BodyClass();
}
[Serializable]
public class BodyClass
{
[XmlElement( ElementName = "element", Namespace = "httpsos")]
public SOSClass element = new SOSClass();
}
[Serializable]
public class SOSClass
{
// This will be used by XML serializer to determine the namespaces
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(
new[] { new XmlQualifiedName("sos", "httpsos"), });
}
}
Run Code Online (Sandbox Code Playgroud)