简体   繁体   中英

Convert plain string to XML format

If I receive a string that is only a list of numbers (eg 1,2,3,5 ), is it possible to convert it to XML format, like this?

<foo>
  <id>1</id>
  <id>2</id>
  <id>3</id>
</foo>

So far I had planned to use something along the lines of this

string s = "example";
XmlDocument xm = new XmlDocument();
xm.LoadXml(string.Format("<foo>{0}</foo>", s));

But I'm unsure as to how I should split the string so that I only get the numbers without using the obvious Split() , which is something my manager doesn't want me to do (otherwise I'd just skip the whole XML format).

Basically, is there a way for me to 'easily' serialize that string into XML format?

You can use the XDocument.Parse(string) method

You can build up the xml string and then pass it to the method

http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.parse.aspx

Use LINQtoXML

string items="1,4,6,3";
XElement elm = new XElement("foo");
foreach(var  item in items.Split(','))
{
    elm.Add(new XElement("id",item));
}

Now ele will have the XML you are looking for

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