【发布时间】:2013-02-12 14:31:18
【问题描述】:
嗯,我是 C# 编程的新手,我需要一点帮助,我试图找到这个问题的答案,但找不到我想要的。可能是我搜索不好,抱歉。
我有这种类型的 xml 文件:
<ROW>
<ID>1256464</ID>
<TEST>
<PROJECT1>
<PROJECT1_ID>984461</PROJECT1_ID>
</PROJECT1>
<PROJECT2>
<PROJECT2_ID>614115</PROJECT2_ID>
</PROJECT2>
<PROJECT3>
<PROJECT3_ID>134998</PROJECT3_ID>
</PROJECT3>
</TEST>
<RESULTS>
<GRADE1>
<GRADE1_ID>6561616</GRADE1_ID>
</GRADE1>
<GRADE2>
<GRADE2_ID>6687979</GRADE2_ID>
</GRADE2>
<GRADE3>
<GRADE3_ID>13156665</GRADE3_ID>
</GRADE3>
</RESULTS>
</ROW>
有很多行,文件很大。所以我应该使用 XmlTextReader 函数。 至少我写了一个小代码:
XmlTextReader reader = new XmlTextReader("items.xml");
while (reader.Read())
{
XmlNodeType nodeType = reader.NodeType;
if (nodeType == XmlNodeType.Element)
{
if (reader.NodeType == "ID")
{
//this node value i get to the console but others not, if them are in depth
Console.WriteLine(reader.ReadString());
}
//tried to do this stuff i know it's wrong
//but i cant get the value of this elment how should i loop through
//and of course i need to reach grade1_id fields and loop through
if (reader.NodeType == "PROJECT2_ID")
{
Console.WriteLine(reader.ReadString());
}
}
}
【问题讨论】:
-
XML 看起来不对 - 我相信
<PROJECT num="1/2/3">...会是正确的选择,否则显然不可能使用 xmltextreader 编写 xml 解析器(还有 dom ......) -
您在谈论确切节点名称的属性是吗?如果是这样,它就无法完成,因为我得到的文件很大并且文件类型看起来像我展示的那样。那么我应该使用什么类型的命名空间呢?
-
我认为他的意思是 XML 应该看起来像:
或者您是说您只是以这种格式获取文件并且必须继续使用它? ...... -
是的,我以这种格式获取数据,我需要循环遍历它。据我所知,节点的属性会更容易,但在我的情况下,我只得到了这种格式。