使用XmlDocument在c#中检索值

问题描述 投票:4回答:2

我正在使用XmlDocument()来解析像我这样的EpubReader应用程序的文件,例如**。opf **。

<item id="W01MB154" href="01MB154.html" media-type="application/xhtml+xml" />
<item id="W000Title" href="000Title.html" media-type="application/xhtml+xml" />

  <itemref idref="W000Title" />
  <itemref idref="W01MB154" />

这些值在同一个文件中。

在这里我知道item的标签中id的值,之后我想知道href元素的值。

我要做的是将itemref标记中的值idref元素与标记项中id的元素值进行比较。在这里我知道id值是W01MB154。

简单地说,我想知道id的下一个值是href元素,使用XmlDocument()。

c# parsing xmldocument
2个回答
5
投票

您可以从以下代码开始。当我执行它时,我得到适当的输出:

string str = @"<?xml version='1.0' encoding='UTF-8'?><root><items><item id='W01MB154' href='01MB154.html' media-type='application/xhtml+xml' /><item id='W000Title' href='000Title.html' media-type='application/xhtml+xml' /></items><itemrefs><itemref idref='W000Title' /><itemref idref='W01MB154' /></itemrefs></root>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // suppose that str string contains the XML data. You may load XML data from a file too.

XmlNodeList itemRefList = xml.GetElementsByTagName("itemref");
foreach (XmlNode xn in itemRefList)
{
    XmlNodeList itemList = xml.SelectNodes("//root/items/item[@id='" + xn.Attributes["idref"].Value + "']");
    Console.WriteLine(itemList[0].Attributes["href"].Value);
}

输出:

000Title.html

01MB154.html

使用的XML是:

<?xml version='1.0' encoding='UTF-8'?>
<root>
    <items>
        <item id='W01MB154' href='01MB154.html' media-type='application/xhtml+xml' />
        <item id='W000Title' href='000Title.html' media-type='application/xhtml+xml' />
    </items>
    <itemrefs>
        <itemref idref='W000Title' />
        <itemref idref='W01MB154' />
    </itemrefs>
</root>

检查XML文档的结构和XPath表达式。


6
投票

下面的代码加载并解析content.opf文件没有任何错误。

要迭代和比较上面的xml,您可以使用以下代码:

try
{
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load("content.opf");

    XmlNodeList items = xDoc.GetElementsByTagName("item");
    foreach (XmlNode xItem in items)
    {
        string id = xItem.Attributes["id"].Value;
        string href= xItem.Attributes["href"].Value;
    }
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.Message);
}
© www.soinside.com 2019 - 2024. All rights reserved.