XmlTextReader的不读元素含量 [英] XMLTextReader not reading an element content
问题描述
static void ReadXml()
{
string a= null;
double b= 0;
double c= 0;
XmlReader xmlReader = new XmlReader("Testxml.xml");
xmlReader.
using (xmlReader)
{
if (xmlReader != null)
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
switch (xmlReader.Name)
{
case "a":
a= xmlReader.ReadElementContentAsString();
break;
case "b":
b= double.Parse(xmlReader.ReadElementContentAsString());
break;
case "c":
c= double.Parse(xmlReader.ReadElementContentAsString());
break;
}
}
}
}
}
}
TestXML内容:
TestXML content:
<a><b>26a83f12c782</b><c>128</c><d>12</d></a>
情况b是从来没有击中。但是,如果我的B结束元素后添加一个空格,情况b被击中。现在,如何让它不改变xml文件的工作?
Case b is never hit. But If I add a space after end element of b, case b is hit. Now how to make it work without changing the xml file?
推荐答案
这是你的代码的工作版本。被纠正的具体问题包括:
Here's a working version of your code. The specific problems that are corrected include:
-
新的XmlReader
不编译。它是一个抽象类。您需要使用的XmlTextReader
或其他的XmlReader
派生类。
new XmlReader
doesn't compile. It's an abstract class. You need to useXmlTextReader
or anotherXmlReader
derived class.
b不是有效的double 。你试图大量十六进制数转换为直接的双重这是不可能的。您可以使用 NumberStyles.HexNumber
在解析
通话,但不能与双击
,它必须是长
或 INT
。
b is not a valid double. You were trying to convert a large hex number to a double directly which isn't possible. You can use NumberStyles.HexNumber
in the Parse
call, but not with double
, it has to be long
or int
.
双读。你叫阅读()
一环内,但然后使用 XmlReader.ReadXxx()
方法为好。这是调用读额外的时间和跳过节点。这真是你问有关的主要问题。下面的代码跟踪中发现的最后一个元素,然后等待,直到它碰到处理文本
节点。这是对简单/平面文档,但是对于更为复杂的你需要跟踪的状态,像一个有限状态机的一种更好的方式。或者使用DOM。 。或LINQ
Double read. You were calling Read()
inside a loop but then using the XmlReader.ReadXxx()
methods as well. This was calling read extra times and skipping nodes. This is really the main problem you were asking about. The following code keeps track of the last element found and then waits till it hits the Text
node for processing. This is fine for simple/flat documents, but for more complex ones you need a better way of keeping track of state, like a finite state machine. Or use DOM. Or LINQ.
static void ReadXml()
{
string a = null;
long b = 0;
double c = 0;
string text = "<a><b>26a83f12c782</b><c>128</c><d>12</d></a>";
string element = "";
using (XmlReader xmlReader = new XmlTextReader(new StringReader(text)))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
element = xmlReader.Name;
}
else if (xmlReader.NodeType == XmlNodeType.Text)
{
switch (element)
{
case "a":
a = xmlReader.Value;
Console.WriteLine("a: " + a);
break;
case "b":
b = long.Parse(xmlReader.Value, NumberStyles.HexNumber);
Console.WriteLine("b: " + b);
break;
case "c":
c = double.Parse(xmlReader.Value);
Console.WriteLine("c: " + c);
break;
}
}
}
}
}
这篇关于XmlTextReader的不读元素含量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!