从C#中的XML序列化中删除父XML元素?

时间:2012-11-20 10:48:07

标签: c# .net xml xml-serialization

我有一个名为Node的类,其中我有类型文档类的属性。

当我将其序列化为XML时,我将输出视为

<Node>
<DocumentType>
<File></File>
</DoumentType>
<Node>

但我希望输出为

<Node>
<File></File>
<Node>

对象代码

public class Document
{
    [XmlElement(ElementName = "file")]
    public string File { get; set; }
}

public class Node
{
    public Document NodeDocument
    {
        get;
        set;
    }
}

我怎样才能使用C#xml序列化?

2 个答案:

答案 0 :(得分:1)

根据Kami的建议,以下是供您参考的代码。归功于Kami。

public class Node : IXmlSerializable {

    public Node() {
        NodeDocument = new Document();
    }

    public Document NodeDocument { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema() {
        return null;
    }

    public void ReadXml(XmlReader reader) {            
        reader.ReadStartElement();
        NodeDocument.File = reader.ReadString();
        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer) {
        writer.WriteStartElement("file");
        writer.WriteString(NodeDocument.File);
        writer.WriteEndElement();
    }
}

public class Document {
    public String File { get; set; }
}

class Program {
    static void Main(string[] args) {
        var node = new Node();
        node.NodeDocument.File = "bbb.txt";

        Serialize<Node>("a.xml", node);

        node = Deserialize<Node>("a.xml");
        Console.WriteLine(node.NodeDocument.File);

        Console.Read();
    }

    static T Deserialize<T>(String xmlFilePath) where T : class {
        using (var textReader = File.OpenText(xmlFilePath)) {
            using (var xmlTextReader = new XmlTextReader(textReader)) {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(xmlTextReader);
            }
        }
    }

    static void Serialize<T>(String xmlFilePath, T obj) where T : class {
        using (var textWriter = File.CreateText(xmlFilePath)) {
            using (var xmlTextWriter = new XmlTextWriter(textWriter)) {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(xmlTextWriter, obj);
            }
        }
    }
}

答案 1 :(得分:0)

您是否考虑过实施IXmlSerializable界面 - http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

然后,您应该能够编写自定义序列化/反序列化以促进上述操作。