簡體   English   中英

讀取XML文件中的下一個值

[英]Read next value in XML file

我有一個像這樣的XML文件:

    <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>

如果鍵是ID,我想讀取下一個<string>

所以我要做的是:

XmlTextReader reader = new XmlTextReader(file);

while (reader.Read())
{
    if (reader.Value.Equals("Id"))
    {
        reader.MoveToNextAttribute
    }  
}

但我沒有成功。

感謝幫助

您可以使用布爾標志來指示是否應讀取下一個元素的值:

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;
    }
}

我想指出的是XmlTextReader基本上被XmlReader取代了

從.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();
        }
    }
}

...

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);
}

雖然要確保它將 正常工作 某些xml與給定的模式不對應而無法快速失敗,您將不得不添加更多的健全性檢查,所以...


如果您不擔心將整個xml樹放入內存中,也可以嘗試LINQ-TO-XML

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);
}

您的XML看起來可疑地類似於Plist 因此,聽起來您需要一個Plist庫。 無需重新發明輪子,只需使用NuGet上可用的任何庫 他們將通過解析XML文件解決您的問題。

如果您堅持要手動解析XML,則無需考慮底層SAX類,而只需使用DOM。 使用XDocument更容易。 請參閱@EugenePodskal的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM