如果我有像这样的xml文件
<?xml version="1.0"?>
<?xml-stylesheet href="catalog.xsl" type="text/xsl"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd">
<catalog>
<product description="Cardigan Sweater" product_image="cardigan.jpg">
<catalog_item gender="Men's">
<item_number>QWZ5671</item_number>
<price>39.95</price>
<size description="Medium">
<color_swatch image="red_cardigan.jpg">Red</color_swatch>
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
</size>
<size description="Large">
<color_swatch image="red_cardigan.jpg">Red</color_swatch>
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
</size>
</catalog_item>
<catalog_item gender="Women's">
<item_number>RRX9856</item_number>
<price>42.50</price>
<size description="Small">
<color_swatch image="red_cardigan.jpg">Red</color_swatch>
<color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
</size>
<size description="Medium">
<color_swatch image="red_cardigan.jpg">Red</color_swatch>
<color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
<color_swatch image="black_cardigan.jpg">Black</color_swatch>
</size>
<size description="Large">
<color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
<color_swatch image="black_cardigan.jpg">Black</color_swatch>
</size>
<size description="Extra Large">
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
<color_swatch image="black_cardigan.jpg">Black</color_swatch>
</size>
</catalog_item>
</product>
</catalog>
如何使用xmlreader获取第一个价格节点的值? 我尝试了下面的代码,但它没有做我想要的...
XmlReaderSettings settings=new XmlReaderSettings();
settings.DtdProcessing=DtdProcessing.Ignore;
XmlReader reader=XmlReader.Create(@"D:\abc.xml",settings);
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name=="price"))
{
Console.WriteLine(reader.ReadInnerXml().First());
}
}
Console.ReadLine();
我在这里缺少什么?
另外我听说 xmlreader 比 Xdocument 更好地读取和写入大型xml文件,如果我放慢速度或崩溃我的程序有多大在具有简单双核CPU和1-2 GB内存的PC上运行它? 我想使用foreach循环读取和修改多个xml文件,并逐个打开每个xml文件并执行读取/修改..
答案 0 :(得分:1)
您的代码返回每个price
元素的第一个字符;你想要返回所有第一个price
元素,然后停止。
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "price"))
{
Console.WriteLine(reader.ReadInnerXml());
break;
}
}