C# 读取XML文件中的下一个值
我有这样一个XML文件:C# 读取XML文件中的下一个值,c#,xml-parsing,readxml,C#,Xml Parsing,Readxml,我有这样一个XML文件: <key>businessAddress</key> <string>Moka</string> <key>businessName</key> <string>Moka address</string> <key>Id</key> <string>39</string>
<key>businessAddress</key>
<string>Moka</string>
<key>businessName</key>
<string>Moka address</string>
<key>Id</key>
<string>39</string>
<key>Cat</key>
<string>216</string>
<key>deals</key>
但我没有成功
感谢您的帮助您可以使用布尔标志指示是否应读取下一个元素的值:
bool shouldReadId = false;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Text && shouldReadId)
{
Console.WriteLine(reader.Value); // will print 39
shouldReadId = false;
}
if (reader.Value.Equals("Id"))
{
// indicate that we should read the value of the next element
// in the next iteration
shouldReadId = true;
}
}
我想指出:
从.NET Framework 2.0开始,我们建议您使用
改为System.Xml.XmlReader类
尽管他们的对象模型没有任何显著的区别
因此,如果您想使用XmlTextReader,可以执行以下操作:
public static class XmlReaderExtensions
{
public static void EnsureRead(this XmlTextReader reader)
{
var isRead = reader.Read();
if (!isRead)
throw new InvalidOperationException("Failed to read");
}
public static void SkipUntil(this XmlTextReader reader, Func<XmlTextReader, Boolean> isStop)
{
while (!isStop(reader))
{
reader.EnsureRead();
}
}
}
您的XML看起来很像。听起来你需要一个Plist库。与其重新发明轮子,不如使用它。他们将解决您解析XML文件的问题 如果您坚持手动解析XML,那么就不要考虑低级SAX类,而只使用DOM。使用
XDocument
要容易得多。参见@EugenePodskal的解决方案
public static class XmlReaderExtensions
{
public static void EnsureRead(this XmlTextReader reader)
{
var isRead = reader.Read();
if (!isRead)
throw new InvalidOperationException("Failed to read");
}
public static void SkipUntil(this XmlTextReader reader, Func<XmlTextReader, Boolean> isStop)
{
while (!isStop(reader))
{
reader.EnsureRead();
}
}
}
var xml = @"<root> <key>businessAddress</key>
<string>Moka</string>
<key>businessName</key>
<string>Moka address</string>
<key>Id</key>
<string>39</string>
<key>Cat</key>
<string>216</string>
<key>deals</key> </root>";
using (var stream = new MemoryStream(Encoding.Default.GetBytes(xml)))
using (var reader = new XmlTextReader(stream))
{
reader.SkipUntil(cur => cur.Value == "Id");
reader.EnsureRead(); // Skip current node
reader.SkipUntil(cur => cur.NodeType == XmlNodeType.Text);
Console.WriteLine("The id from XmlTextReader is {0}", reader.Value);
}
using (var stream = new MemoryStream(Encoding.Default.GetBytes(xml)))
{
var xdoc = XDocument.Load(stream);
var id = xdoc
.Root
.Elements("key")
.First(element =>
element.Value == "Id")
.ElementsAfterSelf("string")
.First()
.Value;
Console.WriteLine("The id from XDocument is {0}", id);
}