将XML数据导出为excel [英] Export XML data to excel
问题描述
XML:
XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<IMPORT ExportDate="2016-03-02" Exercise="1" User="asa" Version="8.73" BusinessUnit="abc(1236)">
<BusinessUnitAdmin>
...
...
</BusinessUnitAdmin>
<BusinessUnit>
..
..
</BusinessUnit>
<Exercise>
..
..
</Exercise>
<Exercise>
..
..
</Exercise>
<Contact>
..
</Contact>
</IMPORT>
我试图将这个xml导出到excel,同时还保持xml的架构。
为此,我尝试将xml转换为Dataset,然后将其导出到excel。
如果我从XML中删除根元素 - IMPORT它可以正常工作。但是因为它有'** BusinessUnit **作为属性,它阻止将BusinessUnit作为元素读取。
为此,我试图从第二个元素` - < businessunitadmin>中读取XML。 ;但无法做到。
C#代码:
I am trying to export this xml to excel, while also maintaining the schema of xml.
For this, i have tried converting the xml to Dataset and then exporting it to excel.
It works correctly if i remove the root element - IMPORT from the XML. However since it has '**BusinessUnit** as attribute, its preventing to read "BusinessUnit" as element.
For this, i am trying to read XML from second element `- <businessunitadmin>` ; but unable to do.
C# Code :
DataSet ds = new DataSet();
string path = "C:\\abc\\xyz.xml";
ds.ReadXml(path); //throwing error
ExportDataSetToExcel(ds);
错误:名为'BusinessUnit'的列已经属于此DataTable:不能将嵌套的表名设置为相同的名称。
我尝试了什么:
我尝试过使用LINQ:
Error : "A column named 'BusinessUnit' already belongs to this DataTable: cannot set a nested table name to the same name."
What I have tried:
I have tried using LINQ :
XDocument xdoc = XDocument.Load(path);
XElement import = xdoc.Element("IMPORT");
XElement contact = import.Element("Contact");
StringReader theReader = new StringReader(contact.ToString());
ds.ReadXml(theReader);
它工作正常,但这样,我必须手动读取所有元素。
我也尝试使用 - var allElements = xdoc.Descendants();
读取元素但无法在数据集中存储特定元素。
请帮忙。
It works correctly,but this way, i have to manually read all elements.
I also tried reading elements using - `var allElements = xdoc.Descendants()`;
but unable to store specfic elements in dataset.
Please help.
推荐答案
哦等等 - 我明白了!
您不能拥有与子元素同名的属性。 BusinessUnit和Exercise用作两者。
要解决此问题,请考虑使用camelCase作为属性,使用TitleCase作为元素:
Oh wait - I see!
You cannot have an attribute with the same name as a child element. "BusinessUnit" and "Exercise" are used as both.
To solve this, consider using camelCase for your attributes and TitleCase for your elements:
<import exportdate="2016-03-02" exercise="1" user="asa" version="8.73" businessunit="abc(1236)">
<businessunitadmin>
...
...
</businessunitadmin>
<businessunit>
..
..
</businessunit>
<exercise>
..
..
</exercise>
<exercise>
..
..
</exercise>
<contact>
..
</contact>
</import>
希望有所帮助^ _ ^
Andy
Hope that helps ^_^
Andy
这篇关于将XML数据导出为excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!