我是一个初级程序员,从C#和web服务开始。
在我的web服务的Service.cs文件中,我创建了一个ReadXMLFile()方法,在该方法中,我试图读取现有的XML文件,从中获取数据,并将其放入我在IService.cs文件中创建的相应属性(DataMembers)。
我的问题是我的代码基本上什么也没做。我试着寻找关于这个的网站和教程,但真的没有太多,特别是对于像我这样的初学者。任何人都知道我应该怎么做,因为我到目前为止一直在尝试的东西显然是错误的。
下面是我的ReadXMLFile()方法。
void ReadXMLFile()
{
XmlTextReader reader = new XmlTextReader("ClassRoll.xml");
reader.Read();
while (reader.Read())
{
if (reader.Name == "id")
{
id = reader.ReadString();
}
else if (reader.Name == "firstname")
{
link = reader.ReadString();
}
else if (reader.Name == "lastname")
{
description = reader.ReadString();
}
else if (reader.Name == "count")
{
description = reader.ReadString();
}
else if (reader.Name == "testscore")
{
description = reader.ReadString();
}
}
}这是我的xml文件的一个示例
<classroll>
<student>
<id>101010</id>
<lastname>Smith</lastname>
<firstname>Joe</firstname>
<testscores count="5">
<score>65</score>
<score>77</score>
<score>67</score>
<score>64</score>
<score>80</score>
</testscores>
</student>
</classroll>发布于 2012-04-14 12:03:50
您可能在while循环中缺少IsStartElement()条件:
while (reader.Read())
{
if (reader.IsStartElement())
{
if (reader.Name == "id")
{
id = reader.ReadString();
}
...
}此外,使用XPath或LINQ to XML读取XML会更容易,当然这取决于文件。这里有一些例子:XPath和LINQ。
编辑:查看XML文件详细信息后
您应该更新您的逻辑以跟踪当前的student及其testscores。还要注意,count是一个属性。它可能很快就会变得混乱,我建议你看看上面提到的样本。
发布于 2013-03-15 17:30:57
我认为,使用XmlDocument可以获得最好的结果
public void ReadXML()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("<name file>.xml");
xmlEntities = new List<XmlEntity>();
foreach(XmlNode item in xmlDoc.ChildNodes)
{
GetChildren(item);
}
}
private void GetChildren(XmlNode node)
{
if (node.LocalName == "Строка")
{
//<you get the element here and work with it>
}
else
{
foreach (XmlNode item in node.ChildNodes)
{
GetChildren(item);
}
}
}发布于 2014-01-09 20:22:51
它不工作的原因是,例如:当reader.Name == "firstname“为真时,它的元素值不是真的。它的确切含义是读取器对象读取下一个节点类型,即XmlNodeType.Element。因此,在本例中,使用reader.Read();函数再次读取下一个节点,即XmlNodeType.Text,其值为Joe。我给你一个工作版本的例子。
void ReadXMLFile()
{
XmlTextReader reader = new XmlTextReader("ClassRoll.xml");
reader.Read();
while (reader.Read())
{
if (reader.Name == "id")
{
reader.Read();
if(reader.NodeType == XmlNodeType.Text)
{
id = reader.Value;
reader.Read();
}
}
}}
https://stackoverflow.com/questions/10150785
复制相似问题