[英]Check XML node have attribute name with specific value - Parse XML using Linq
首先,我为使用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>
我正在尝试检查具有属性epub:type
nav
标签epub:type
值为toc
&进入&
为了实现这一点,我开始获得<nav>
标签,该标签具有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; } }
但每次result
计数为零。 我想知道我的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
语句中的结果,只需在Descendants
调用结束时调用.ToList()
:
foreach (var t in xDoc.Descendants(ns + "nav").ToList())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.