我正在尝试从xml文件中读取一些部分,但它只是先读取,为什么?
这是代码:
using (XmlReader reader = XmlReader.Create("settings.xml"))
{
if(reader.ReadToFollowing("LastProcessingId"))
Console.Write(reader.ReadElementContentAsInt());
if(reader.ReadToFollowing("TotalNumberFolders"))
Console.Write(reader.ReadElementContentAsInt());
if(reader.ReadToFollowing("LastAccessTime"))
Console.Write(reader.ReadElementContentAsDateTime());
}
似乎第二次调用reader.ReadToFollowing在调用此行Console.Write(reader.ReadElementContentAsInt());
之后不起作用
xml文件是:
<Settings>
<LastProcessingId>3</LastProcessingId>
<TotalNumberFolders>20</TotalNumberFolders>
<LastAccessTime>2014-05-06T00:00:00+04:00</LastAccessTime>
</Settings>
这是为我工作的代码
using (XmlReader reader = XmlReader.Create("settings.xml"))
{
reader.MoveToContent();
while(reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine("{0}: ",reader.Name);
// Next read will contain text.
if (reader.Read()) Console.WriteLine("{0}: ", reader.Value);
}
}
}
一年过去了,但没有人真正回答OP的问题。 ReadToFollowing应该用于查找第一个节点然后使用ReadToNextSibling应该用作described here。例:
using (XmlReader reader = XmlReader.Create("books.xml")) {
reader.ReadToFollowing("book");
do {
Console.WriteLine("ISBN: {0}", reader.GetAttribute("ISBN"));
} while (reader.ReadToNextSibling("book"));
}
读取所有节点使用:
while (reader.Read())
{
}
但我使用Linq读取XML:
<customers>
<customer id="84">
<name value="Sample Name" />
</customer>
<customer id="89">
<name value="Sample Name 2" />
</customer>
<customer id="80">
<name value="Sample Name 3" />
</customer>
</customers>
使用此代码:
XmlNode searched = null;
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Temporary\customers.xml");
foreach (XmlNode node in doc.SelectNodes("/customers/customer"))
{
}
要么
XElement main = XElement.Load(@"D:\Temporary\customers.xml");
IEnumerable<XElement> searched =
from c in main.Elements("customer")
select c;