将XML元素作为DataTable列读取

时间:2014-06-20 12:33:25

标签: c# .net

我正在使用xml

<B>
<B_A>pfd_exch_asia_bbid.px.hpc</B_A>
<B_A>pfd_exch_asia_bbid.dif</B_A>
<B_A>pfd_exch_asia.cax</B_A>
<B_A>pfd_exch_asia_bbid.px</B_A>
<B_A>pfd_exch_asia_bbid.out</B_A>
<B_E>pfd_exch_euro_bbid.px</B_E>
<B_E>pfd_exch_euro_bbid.px.hpc</B_E>
<B_E>pfd_exch_euro_bbid.dif</B_E>
<B_E>pfd_exch_euro_bbid.out</B_E>
<B_E>pfd_exch_euro.cax</B_E>
</B>

我希望表 B 是唯一的表, B_A B_E 是列,但当我将其作为数据集全部读取时三个人来到不同的桌子。

1 个答案:

答案 0 :(得分:0)

试试这种方式

            DataTable dtValues = new DataTable();
            string strFilePath = FilePath + strFilename;

            XmlDataDocument xml = new XmlDataDocument();
            xml.Load(strFilePath);

            var nsmgr = new XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");

            XmlNodeList firstNode = xml.SelectNodes("ss:Workbook/ss:Worksheet/ss:Table/ss:Row[@ss:Index='1']", nsmgr);

            XmlNodeList nodeParam = xml.SelectNodes("ss:Workbook/ss:Worksheet/ss:Table/ss:Row", nsmgr);

            StringBuilder sb = new StringBuilder();
            DataTable dtValuesNew = new DataTable();
            dtValuesNew.Columns.Add("columnValue", typeof(string));
            int colCount = nodeParam[0].ChildNodes.Count;
            foreach (XmlNode node in nodeParam)
            {
                dtValues = new DataTable();
                dtValues.Columns.Add("columnIndex", typeof(string));
                dtValues.Columns.Add("columnValue", typeof(string));

                foreach (XmlNode childNode in node.ChildNodes)
                {
                    dtValues.Rows.Add(childNode.Attributes[0].Value.ToString(), childNode.InnerText);
                }
                sb = new StringBuilder();

                dtValuesNew.Rows.Add(sb.ToString());
            }