Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查XML节点是否具有具有特定值的属性名称-使用Linq解析XML_C#_Xml_Linq_Parsing - Fatal编程技术网

C# 检查XML节点是否具有具有特定值的属性名称-使用Linq解析XML

C# 检查XML节点是否具有具有特定值的属性名称-使用Linq解析XML,c#,xml,linq,parsing,C#,Xml,Linq,Parsing,首先,我很抱歉提出了一个关于使用Linq进行XML解析的新问题 <?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">

首先,我很抱歉提出了一个关于使用Linq进行XML解析的新问题

<?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>
但每次
结果
计数都为零。我想知道我的XML有什么问题

你能告诉我正确的方法吗


谢谢。

这是一个名称空间问题。您正在查找
nav
元素,但未指定名称空间,但默认名称空间为
”http://www.w3.org/1999/xhtml“
。此外,您正在以错误的方式查找epub属性

我建议您将代码更改为:

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
    }
}
或者,如果要在
if
语句中修改结果,只需在
子体的末尾调用
.ToList()

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