Kum*_*mar 4 c# parsing xmldocument
我XmlDocument()用于解析文件,如*.opf*,用于我的EpubReader应用程序.
<item id="W01MB154" href="01MB154.html" media-type="application/xhtml+xml" />
<item id="W000Title" href="000Title.html" media-type="application/xhtml+xml" />
Run Code Online (Sandbox Code Playgroud)
同
<itemref idref="W000Title" />
<itemref idref="W01MB154" />
Run Code Online (Sandbox Code Playgroud)
这些值在同一个文件中..
在这里我知道了item的标签中id的值,之后我想知道href元素的值.
我需要做的是比较值IDREF在elemnt 的itemref用的元素值标签ID的标签项目.在这里我知道id值是W01MB154.
简单地说,我想知道id的下一个值是href元素,使用XmlDocument(),
如果有人意识到这种情况,请帮帮我.
谢谢,
下面的代码加载并解析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);
}
Run Code Online (Sandbox Code Playgroud)
您可以从以下代码开始.当我执行它时,我得到适当的输出:
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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
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>
Run Code Online (Sandbox Code Playgroud)
检查XML文档的结构和XPath表达式.
| 归档时间: |
|
| 查看次数: |
22137 次 |
| 最近记录: |