Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

c# - Xml.Linq: Descendants() returns nothing

I am trying to read from an ncx file (i.e. xml file) using XElement:

XElement foundNode = ncx.Descendants("navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault();

As a result, foundNode is null because ncx.Descendants("navPoint") returns an empty enumeration. But the data is there:

<?xml version='1.0' encoding='utf-8'?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en">
  <head>
    <meta content="8eab2efe-d584-478a-8c73-1304d2ae98fa" name="dtb:uid"/>
    <meta content="3" name="dtb:depth"/>
    <meta content="calibre (0.8.12)" name="dtb:generator"/>
    <meta content="0" name="dtb:totalPageCount"/>
    <meta content="0" name="dtb:maxPageNumber"/>
  </head>
  <docTitle>
    <text>Fine</text>
  </docTitle>
  <navMap>
    <navPoint class="chapter" id="27665f37-ecf5-4934-a044-4f77152e54d9" playOrder="1">
      <navLabel>
        <text>I. BLIND</text>
      </navLabel>
      <content src="Fine_split_003.html"/>

Could you please explain what is wrong here? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to take namespace in XML into account:

XDocument ncx = XDocument.Load("file.xml");
XNamespace df = ncx.Root.Name.Namespace;
XElement foundNode = ncx.Descendants(df + "navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...