[英]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.