本文介绍了如何将字符串数组写入xml格式的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串数组:mainstring = peter|100|john|200|sue|300
并希望将其转换为类似于-
的xml字符串
I have a string array:mainstring = peter|100|john|200|sue|300
and want to convert it into an xml string that looks like-
<xml>
<identity>
<id><name>peter</name><salary>100</salary></id>
<id><name>john</name><salary>200</salary></id>
<id><name>sue</name><salary>300</salary></id>
</identity>
</xml>
注意:mainstring在数组中可以包含更多名称和薪水值,因此代码必须是动态的
非常感谢您的帮助!!!!!
Note: the mainstring can have more names and salary values in array, so the code has to be dynamic
Any help is greatly appreciated!!!!
推荐答案
mainstring = "peter|100|john|200|sue|300";
string[] data = mainstring.Split('|'); // Split data
XElement identity = new XElement("identity"));
// Walk array of data
for (int count = 0; count < data.Length; count += 2)
{
XElement elm = new XElement("id",
new XElement("name", data[count]),
new XElement("salary", data[count + 1]));
identity.Add(elm);
}
XElement xml = new XElement("xml", identity);
输出"xml"变量XElement:
Output of "xml" variable XElement:
<xml>
<identity>
<id><name>peter</name><salary>100</salary></id>
<id><name>john</name><salary>200</salary></id>
<id><name>sue</name><salary>300</salary></id>
</identity>
</xml>
我还没有编译它或任何测试.刚好快用完内存.
祝你好运!
I have not compiled it or any test. Just right out of memory.
Good luck!
string[] names = { "KRISH", "JOHN" };
using (XmlWriter writer = XmlWriter.Create(@"D:\sample.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Names");
foreach (string name in names)
{
writer.WriteStartElement("Name");
writer.WriteElementString("FirstName", name.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
这篇关于如何将字符串数组写入xml格式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!