简体   繁体   English

将纯字符串转换为XML格式

[英]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? 如果我收到的字符串只是数字列表(例如1,2,3,5 ),是否可以像这样将其转换为XML格式?

<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). 但是我不确定如何分割字符串,以便只获得数字而不使用明显的Split() ,这是我的经理不希望我做的事情(否则,我将跳过整个XML格式)。

Basically, is there a way for me to 'easily' serialize that string into XML format? 基本上,有没有一种方法可以让我轻松地将该字符串序列化为XML格式?

You can use the XDocument.Parse(string) method 您可以使用XDocument.Parse(string)方法

You can build up the xml string and then pass it to the method 您可以构建xml字符串,然后将其传递给方法

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

Use LINQtoXML 使用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 现在ele将拥有您要寻找的XML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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