使用XmlDocument检索c#中的值 [英] Using XmlDocument to Retrieve values in c#

查看:79
本文介绍了使用XmlDocument检索c#中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XmlDocument()解析EpubReader应用程序中的**.opf **之类的文件.

I am using XmlDocument() for parsing a file like **.opf ** for my application of EpubReader.

<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 元素的值.

Here I know the value of id within the tag of item, after that I want to know the value of the href element.

我要做的是将 itemref 标签中的值 idref 元素与标签中的元素值 id 进行比较项目.在这里,我知道 id 值,即 W01MB154 .

What I have to do is compare the value idref element in the itemref tag with element value of id in the tag item. Here I know the id value which is W01MB154.

简而言之,我想使用XmlDocument()了解 id 的下一个值,即 href 元素.

Simply, I want to know the next value of id which is href element, Using XmlDocument().

推荐答案

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

You may start with the following code. When I execute it, I get proper output:

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

000Title.html

01MB154.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表达式的结构.

Check the structure of the XML document and the XPath expression.

这篇关于使用XmlDocument检索c#中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆