[英]Read XML Document using C# or Java
I want to read below XML format only some attributes are required not All. 我想阅读以下XML格式,仅需要一些属性,而不是全部。 For Eg: 例如:
<Parts>
- <Part>
<Section>3003512</Section>
<Mark>RP-103</Mark>
<Length>4950</Length>
- <Components>
<Section>3003512</Section>
<Mark>RP-103</Mark>
<Length>4950</Length>
<Remark>System Generated </Remark>
<Components />
<Remark>No Comments </Remark>
</Part>
- <Part>
<Section>3003512</Section>
<Mark>RP-103</Mark>
<Length>4950</Length>
<Components />
<Remark>No Comments </Remark>
</Part>
</Parts>
I want to Read Only Sections and Mark in Tabular Format. 我想只读节并以表格格式标记。 I am using below code to read this But it is giving Error Table Schema 'Component' Already Exists . 我正在使用下面的代码来阅读此内容,但它给出了错误表架构“组件”已存在。
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Mark");
DataColumn dc1 = new DataColumn("Sections ");
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
DataSet dSet = new DataSet();
if (File.Exists(xmlpath2))
{
XmlTextReader Reader1 = new XmlTextReader(xmlpath2);
dSet.ReadXml(Reader1, XmlReadMode.Auto);
for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
{
DataRow rows = dSet.Tables[0].Rows[i];
DataRow myRow = dt.NewRow();
myRow["Mark"] = rows["Mark"];
myRow["Sections "] = rows["Sections "];
dt.Rows.Add(myRow);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
was doing something simiar a while back: LINQ multiple columns 前段时间在做类似的事情: LINQ多列
hope should get you on the right track 希望能使您走上正确的道路
Here's an example using LINQ to XML : 这是一个使用LINQ to XML的示例:
var ele = XElement.Parse(xml); // change to XElement.Load if loading from file
var result = ele.Descendants("Section")
.Zip(ele.Descendants("Mark"),
(s,m) => new {Section = s.Value, Mark = m.Value});
Now you can create your DataTable
: 现在,您可以创建DataTable
:
var table = new DataTable();
var marks = new DataColumn("Mark");
var sections = new DataColumn("Sections");
table.Columns.Add(marks);
table.Columns.Add(sections);
foreach (var item in result)
{
var row = table.NewRow();
row["Mark"] = item.Mark;
row["Sections"] = item.Section;
table.Rows.Add(row);
}
This will produce: 这将产生:
Mark Sections
RP-103 3003512
RP-103 3003512
RP-103 3003512
It assumes that each Section
is followed by a single and corresponding Mark
. 假定每个Section
后面都有一个单独的对应Mark
。 It also requires System.Xml.Linq
and System.Linq
. 它还需要System.Xml.Linq
和System.Linq
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.