Using XmlDocument to Retrieve values in c#

ぃ、小莉子 提交于 2019-12-01 06:16:44

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

Output:

000Title.html

01MB154.html

The XML used is:

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

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

Munawar

Following code loads and parses content.opf file without any error.

To iterate and compare above xml you may use following code:

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!