【发布时间】:2013-12-30 12:59:41
【问题描述】:
我想像这样解析一个 XML 文件:
<?xml version="1.0" encoding="utf-8" ?>
<database name="myDb">
<table name="myTable">
<field name="Code" type="int" size="0" identity="true" primarykey="true" description="کد شناسه" reference=""></field>
<field name="Name" type="nvarchar" size="50" identity="false" primarykey="false" description="نام شخص" reference=""></field>
</table>
<table name="yourTable">
<field name="Code" type="int" size="0" identity="true" primarykey="true" description="کد شناسه" reference=""></field>
<field name="Title" type="nvarchar" size="50" identity="false" primarykey="false" description="نام شخص" reference=""></field>
</table>
</database>
问题在于,在我的内部 foreach 中,它将解析 4 个字段,而不是与每个表相关的 2 个字段。如何将代码更改为只读取当前表的字段?
XDocument xdoc = XDocument.Load("d:\\tables.xml");
foreach (XNode table in xdoc.Descendants("database").Nodes())
{
fields = "";
tableName = XElement.Parse(table.ToString()).Attribute("name").Value;
//XElement xE = XElement.Parse(table.ToString());
//foreach (XElement e in xE.Elements())
foreach (XNode field in xdoc.Descendants("table").Nodes())
{
fieldName = XElement.Parse(field.ToString()).Attribute("name").Value;
type = XElement.Parse(field.ToString()).Attribute("type").Value;
size = XElement.Parse(field.ToString()).Attribute("size").Value;
identity = XElement.Parse(field.ToString()).Attribute("identity").Value;
primarykey = XElement.Parse(field.ToString()).Attribute("primarykey").Value;
description = XElement.Parse(field.ToString()).Attribute("description").Value;
reference = XElement.Parse(field.ToString()).Attribute("reference").Value;
if (identity == "true") identity = "identity";
if (primarykey == "true") primarykey = "primary key";
if (isChar(type))
{
fields += string.Format(fieldCharTemplate, fieldName, type, size);
}
else
{
fields += string.Format(fieldNonCharTemplate, fieldName, type, identity,primarykey);
}
//var y = x.Element("type");
}
sql = string.Format(tableTemplate, tableName, fields);
Response.Write(sql);
}
【问题讨论】:
标签: c# xml xml-parsing linq-to-xml