我正在寻找一个很好的例子,使用c#
的XmlReader
读取格式正确且有效的xml文件(附加外部dtd)
用谷歌搜索并阅读了书籍,但找不到一个好的,解释良好的例子。
这是XML文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Catalog SYSTEM "marketplace_feed_v2.dtd">
<Catalog>
<Category>
<Name>Arts & Entertainment</Name>
<Site>
<Id>ABC CORP</Id>
<PopularityRank>1</PopularityRank>
<Title><![CDATA[Some Description]]></Title>
<Description><![CDATA[Don't Have A Website? Create A Money Making Website]]></Description>
<HasRecurringProducts>true</HasRecurringProducts>
<Gravity>432.74</Gravity>
<PercentPerSale>75.0</PercentPerSale>
<PercentPerRebill>45.0</PercentPerRebill>
<AverageEarningsPerSale>28.14599</AverageEarningsPerSale>
<InitialEarningsPerSale>25.3445</InitialEarningsPerSale>
<TotalRebillAmt>28.55413</TotalRebillAmt>
<Referred>95.0</Referred>
<Commission>75</Commission>
<ActivateDate>2009-06-29</ActivateDate>
</Site>
</Categoty>
<Category><Site>....</Site></Category></Catalog>
这是DTD文件:
<!ELEMENT Catalog ( Category* ) >
<!ELEMENT Category ( Name, Site*, Category* ) >
<!ELEMENT Commission ( #PCDATA ) >
<!ELEMENT Description ( #PCDATA ) >
<!ELEMENT InitialEarningsPerSale ( #PCDATA ) >
<!ELEMENT AverageEarningsPerSale ( #PCDATA ) >
<!ELEMENT TotalRebillAmt ( #PCDATA ) >
<!ELEMENT HasRecurringProducts ( #PCDATA ) >
<!ELEMENT Gravity ( #PCDATA ) >
<!ELEMENT Id ( #PCDATA ) >
<!ELEMENT Name ( #PCDATA ) >
<!ELEMENT PercentPerSale ( #PCDATA ) >
<!ELEMENT PercentPerRebill ( #PCDATA ) >
<!ELEMENT PopularityRank ( #PCDATA ) >
<!ELEMENT ActivateDate ( #PCDATA ) >
<!ELEMENT Site ( Commission? | Site+ | InitialEarningsPerSale? | AverageEarningsPerSale? | TotalRebillAmt? | Gravity? | Id+ | PercentPerSale? | PercentPerRebill? | PopularityRank+ | Title+ | HasRecurringProducts | ActivateDate? )* >
<!ELEMENT Title ( #PCDATA ) >
任何人都可以帮我一个例子吗?
答案 0 :(得分:1)
发现XmlReader
是只读且仅向前的。
所以用这个
StreamReader stream = new StreamReader(filePath);
XmlReader reader = XmlReader.Create(stream, settings);
while (reader.Read())
{
reader.MoveToContent();
// Parse the file and display each of the nodes.
while (reader.Read())
{
reader.MoveToElement();
if (reader.Name.Equals("Category") && reader.NodeType != XmlNodeType.EndElement)
{
Response.Write("<b>" + reader.Name + "</b>" + "<br/>");
}
else if (reader.Name.Equals("Name") && reader.NodeType != XmlNodeType.EndElement)
{
Response.Write("<span style='color:#1884A5'>" + reader.Name + "</span>" + " : ");
Response.Write(reader.ReadElementString() + "<br/>");
}
}
如果有更好的例子......我会很感激..
答案 1 :(得分:0)
我会尝试给XLINQ,阅读:LINQ to XML示例并尝试一下。
它应该非常简单,直接,并且很容易编辑。