简体   繁体   中英

Check XML node have attribute name with specific value - Parse XML using Linq

First I apologize for creating a new question about XML parsing using Linq

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
    xmlns:epub="http://www.idpf.org/2007/ops">
    <head>
        <meta charset="utf-8"></meta>       
        <link rel="stylesheet" type="text/css" href="epub.css"/> 
    </head>
    <body>
        <nav epub:type="toc" id="toc">          
            <ol>
                <li>
                    <a href="text.xhtml">The System</a>
                </li>   
                    <li>
                    <a href="text1.xhtml">The Option</a>
                </li>   
            </ol>           
        </nav>
           <nav epub:type="landmarks" id="guide">
            .......
            .......
           </nav>
    </body>
</html>

I am trying to check nav tag having the attribute epub:type with value toc & which get into &

  • tags collect all tag info.

    To achieve this I started to get the <nav> tag which having attreibute epub:type with value toc

      var xDoc = XDocument.Load("nav.xhtml"); var result = (from ele in xDoc.Descendants("nav") select ele).ToList(); foreach (var t in result) { if (t.Attributes("epub:type").Any()) { var dev = t.Attribute("epub:type").Value; } } 

    But every time the result count is zero. I wonder what is the wrong in my XML.

    Can you please suggest me right way.

    Thanks.

  • This is a namespace problem. You're looking for nav elements without specifying a namespace, but the default namespace is "http://www.w3.org/1999/xhtml" . Additionally, you're looking for your epub attributes in the wrong way.

    I suggest you change your code to:

    var xDoc = XDocument.Load("nav.xhtml");
    XNamespace ns = "http://www.w3.org/1999/xhtml";
    XNamespace epub = "http://www.idpf.org/2007/ops";
    
    foreach (var t in xDoc.Descendants(ns + "nav"))
    {
        var attribute = t.Attribute(epub + "type");
        if (attribute != null)
        {
            ... use the attribute
        }
    }
    

    Or if you want to modify the result in your if statement, just call .ToList() at the end of the Descendants call:

    foreach (var t in xDoc.Descendants(ns + "nav").ToList())
    

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM