在c#中将XML转换为List [英] convert XML to List in c#

查看:1666
本文介绍了在c#中将XML转换为List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml string.i想要将xml字符串转换为List.so,我可以获取c1,c2,... cn的所有数据。



如果c1,c2 ....列是固定的,那么很容易通过类对象转换列表。

但是这里它没有修复。请帮我。下面是我的xml文件。

Hi,i have a xml string.i want to convert the xml string to a List.so that i can fetch all the data of c1,c2, ...cn.

if the c1 ,c2 .... columns are fixed ,then easy to convert a list through a class object.
but here it is not fixed.please help me.below is my xml file.

<root>

<columns>

    <column>
        <c1>100</c1>
        <c2>200</c2>
        <cn>300</cn>
    </column>

    <column>
        <c1>111</c1>
        <c2>222</c2>
        <cn>333</cn>
    </column>

    <column>
        <c1>MAX Newsletter</c1>
        <c2>OLS Application</c2>
        <cn>Total funded accounts</cn>
    </column>

</columns>


</root>

推荐答案

您好,



这将帮助您实现目标你的目标。试试这个。



Hi,

This will help you in achieving your goal. Try this out.

XmlDocument doc = new XmlDocument();
     doc.Load("D:\\testpp.xml");
     ArrayList list = new ArrayList();
     XmlNode idNodes = doc.SelectSingleNode("columns/column");
     foreach (XmlNode node1 in idNodes.ChildNodes)
         list.Add(node1.InnerText);





在此,您可以获得列表中列出的所有后续项目。无论您提到的元素数量如何,它都可以正常工作。



如果您遇到任何问题,请告诉我。



谢谢,

Sisir Patro



In this you can able to get all the subsequent items listed in the list. It will work irrespective of your number of elements as you have mentioned.

If you face any issues please let me know.

Thanks,
Sisir Patro


试试这个。请从字符串中删除 root 元素

Try this. Please remove the root element from the string
[XmlRoot(ElementName = "column")]
   public class Row
   {
       public string C1 { get; set; }
       public string C2 { get; set; }
       public string Cn { get; set; }
   }
 const string xmlString = @"<columns><column><c1>100</c1><c2>200</c2><cn>300</cn></column><column><c1>111</c1><c2>222</c2><cn>333</cn></column> <column>  <c1>MAX Newsletter</c1><c2>OLS Application</c2>  <cn>Total funded accounts</cn> </column></columns>";
           XDocument doc = XDocument.Parse(xmlString);
           if (doc.Root != null)
           {
               List<Row> items = (from r in doc.Root.Elements("column")
                            select new Row
                                       {
                                           C1 = (string)r.Element ("c1"),
                                           C2 = (string)r.Element("c2"),
                                           Cn = (string)r.Element("cn")
                                       }).ToList();
           }





希望这有帮助



Hope this helps


这篇关于在c#中将XML转换为List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆