【问题标题】:XML Load repeated elements using c#XML使用c#加载重复的元素
【发布时间】:2018-11-15 09:50:32
【问题描述】:

是否可以循环具有相同字段方向的元素。

<?xml version="1.0" encoding="utf-8"?>
<xml>
    <document>
        <sls>                                           
            <ppsitecode>0062</ppsitecode>                                           
            <ppsitedesc><![CDATA[AAAAAAA]]></ppsitedesc>                                            
            <ppqty>1.00</ppqty>                                         
            <ppunit>C24</ppunit>                                            
            <ppsitecode>0269</ppsitecode>                                           
            <ppsitedesc><![CDATA[BBBBBBB]]></ppsitedesc>                                            
            <ppqty>1.00</ppqty>                                         
            <ppunit>C24</ppunit>                                            
            <ppsitecode>2546</ppsitecode>                                           
            <ppsitedesc><![CDATA[CCCCCCC]]></ppsitedesc>                                            
            <ppqty>1.00</ppqty>                                         
            <ppunit>C24</ppunit>
        </sls>
    </document>
</xml>

使用上面的xml文件。请参考下面的愿望输出:

ppsitecode   ppsitedesc   ppqty     ppunit
0062         AAAAAAA      1.00      C24
0269         BBBBBBB      1.00      C24
2546         CCCCCCC      1.00      C24

【问题讨论】:

    标签: c# xml xmldocument


    【解决方案1】:

    使用 xml linq:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.Data;
    
    namespace ConsoleApplication83
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                XElement sls = doc.Descendants("sls").FirstOrDefault();
    
                DataTable dt = new DataTable();
                string[] columns = sls.Elements().Select(x => x.Name.LocalName).Distinct().ToArray();
    
                foreach (string column in columns)
                {
                    dt.Columns.Add(column, typeof(string));
                }
    
                DataRow newRow = null;
                foreach (XElement element in sls.Elements())
                {
                    string columnName = element.Name.LocalName;
                    if (columnName == "ppsitecode") newRow = dt.Rows.Add();
    
                    newRow[columnName] = (string)element;
                }
    
    
            }
    
    
    
        }
    
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多