简体   繁体   中英

How to define a string array element to a cdata node in xml x#

I need to serialize a class to XML which looks like

<Dummy>
  <Definition>
  </Definition>
  <Example><![CDATA[0401010101010101]]></Example>
  <Example><![CDATA[0401010101010101]]></Example>
  <Example><![CDATA[0401010101010101]]></Example>      
</Dummy>

The number of "Example" nodes can vary from 3 nodes to n number of nodes. So i need to define it as a string array in my xml class. How should my class look like ???

I saw an example online for a string:

[XmlIgnore]
public string Example { get; set; }

[XmlElement("Example")]
public System.Xml.XmlCDataSection MyStringCDATA
{
    get
    {
        return new System.Xml.XmlDocument().CreateCDataSection(Example);
    }
    set
    {
        Example = value.Value;
    }
}

But I have a string array.

How do I define it?

This is the only class you need to read in the List of strings (Example).

[XmlRoot(ElementName = "Dummy")]
public class Dummy
{
    [XmlElement(ElementName = "Definition")]
    public string Definition { get; set; }
    [XmlElement(ElementName = "Example")]
    public List<string> Example { get; set; }
}

Usage:

XmlSerializer serializer = new XmlSerializer(typeof(Dummy));
Dummy obj = (Dummy)serializer.Deserialize(new StreamReader(filename));
List<string> examples = obj.Example;
examples.ForEach(x => Console.WriteLine(x));

Output

0401010101010101
0401010101010101
0401010101010101

Alternate

If you are looking to get the entire value within example, you will have to do something like this. Reason behind that is values are surrounded with <> which makes the value an element (without an end tag).

XDocument xdoc = XDocument.Parse(xmlString);
var objects = xdoc.Root.Elements().Where(x => x.Name.ToString().Equals("Example")).ToList();
objects.ForEach(x => Console.WriteLine(x.FirstNode.ToString()));

which produces the output of:

<![CDATA[0401010101010101]]>
<![CDATA[0401010101010101]]>
<![CDATA[0401010101010101]]>

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