删除p2:type =“&lt; <type>&gt;”来自xml的xmlns:p2 =“http://www.w3.org/2001/XMLSchema-instance”

时间:2017-06-24 10:47:28

标签: c# xml xml-serialization

如何从xml的所有内部节点中删除xmlns。我能够从根节点中删除xmlns,但内部节点仍然具有内部节点中的所有xmlns。

public class Program
{
    public static void Main()
    {

        List<Person> students = new List<Person>();

        Student std1 = new Student() { Name="Name1", StudentId = 1};
        students.Add(std1);

        Student std2 = new Student() { Name = "Name2", StudentId = 2 };
        students.Add(std2);

        string data = students.ToList().ToXML();
    }
}

[System.Xml.Serialization.XmlInclude(typeof(Student))]
public class Person
{
    public string Name { get; set; }
}

public class Student : Person
{
    public int StudentId { get; set; }
}

toxml用于()

public static string ToXML<T>(this T value)
    {
        if (value.IsNull()) return string.Empty;

        var xmlSerializer = new XmlSerializer(typeof(T));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");

        using (var stringWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false }))
            {
                xmlSerializer.Serialize(xmlWriter, value, ns);
                return stringWriter.ToString();
            }
        }
    }

输出

<ArrayOfPerson>
    <Person p2:type="Student" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance">
        <Name>Name1</Name>
        <StudentId>1</StudentId>
    </Person>
    <Person p2:type="Student" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance">
        <Name>Name2</Name>
        <StudentId>2</StudentId>
    </Person>
</ArrayOfPerson>

预期输出

<ArrayOfPerson>
    <Person>
        <Name>Name1</Name>
        <StudentId>1</StudentId>
    </Person>
    <Person>
        <Name>Name2</Name>
        <StudentId>2</StudentId>
    </Person>
</ArrayOfPerson>

3 个答案:

答案 0 :(得分:0)

在代码中执行XML序列化后,您可以应用此答案中的RemoveAllNamespaces()函数: How to remove all namespaces from XML with C#?

答案 1 :(得分:0)

这是添加的,因为您正在序列化Person的列表,但使用的是Student的子类型。序列化程序需要类型属性来确定所使用的实际类型。

如果您不想要这些属性并且只有一种类型的“人”,那么您应该折叠StudentPerson的定义:

public class Person
{
    public string Name { get; set; }
    public int StudentId { get; set; }
}

答案 2 :(得分:0)

[XmlElement("Person", Type = typeof(Student))]
List<Person> students = new List<Person>();

然后删除您的包含 永远让我想通这个