简体   繁体   中英

Is it possible to specify a XML node name and depth with attributes

I would like to serialize a C# class structure out to XML and provide for a specific node name without having to have a bunch of nested classes. Is that possible using attributes?

For example say I have the following XML:

<OuterItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <InnerItem>
        <ItemValue>something i need</ItemValue>
    </InnerItem>
</OuterItem>

I have an XML serialization method that looks like this:

public static string XmlSerializeToString<T>(T value)
{
    if (value == null) { return null; }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = false;
    settings.OmitXmlDeclaration = true;

    using (StringWriter textWriter = new StringWriter())
    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
    {
        serializer.Serialize(xmlWriter, value);
        return textWriter.ToString();
    }
}

Would I have to have a C# class structure like this?

public class OuterItem
{
    public InnerItem InnerItem { get; set; }
}

public class InnerItem
{
    public string ItemValue { get; set; }
}

Or is it at all possible to declare how far down in the XML document my node should be with something like this (pseudo code):

public class OuterItem
{
    [XmlNode("InnerItem\ItemValue")]
    public string ItemValue { get; set; }
}

No, it is not possible to use xpath or similar expressions in XmlNode attributes. Your choice of attributes to control xml serialization is very limited.

You can use following hack to deserialize xml you have:

public class OuterItem
{
    [XmlArrayItem(ElementName="ItemValue", Type=typeof(string))]
    [XmlArray]
    public string[] InnerItem
    {
        get; set;
    }
}

public class Test
{
    static void Main()
    {
        var item = new OuterItem { InnerItem = new[]{"AAA"} };
        XmlSerializer ser = new XmlSerializer(typeof(OuterItem));
        ser.Serialize(Console.Out,item);
    }
}

This would produce following xml:

<?xml version="1.0" encoding="utf-8"?>
<OuterItem xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <InnerItem>
    <ItemValue>AAA</ItemValue>
  </InnerItem>
</OuterItem>

Another possible solution is to use XmlTextAttribute, get inner xml into property of XmlNode type, and parse manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM