给定以下 XML
<?xml version="1.0" encoding="utf-8" ?>
<headtags>
<tags page-path-from-root="Models/ModelDashboard">
<tag type="title" value=""></tag>
<tag type="meta" name="keyword" content=""></tag>
<tag type="meta" name="description" content=""></tag>
<tag type="meta" name="author" content=""></tag>
<tag type="link" rel="canonical" href="" />
<tag type="meta" property="og:locale" content="en_US" />
<tag type="meta" property="og:type" content="website" />
<tag type="meta" property="og:title" content="Model Dashboard" />
<tag type="meta" property="og:description" content="Dashboard of values for a {model}" />
<tag type="meta" property="og:site_name" content="Car Collector Data" />
<tag type="meta" property="article:publisher" content="Group LLC" />
<tag type="meta" property="article:author" content="me" />
</tags>
<tags page-path-from-root="Identity/Account/Manage/SiteStatus">
<tag type="title" value=""></tag>
<tag type="meta" name="keyword" content=""></tag>
<tag type="meta" name="description" content=""></tag>
<tag type="meta" name="author" content=""></tag>
<tag type="link" rel="canonical" href="" />
<tag type="meta" property="og:locale" content="en_US" />
<tag type="meta" property="og:type" content="" />
<tag type="meta" property="og:title" content="" />
<tag type="meta" property="og:description" content="" />
<tag type="meta" property="og:url" content="" />
<tag type="meta" property="og:site_name" content="" />
<tag type="meta" property="article:publisher" content="" />
<tag type="meta" property="article:author" content="" />
</tags>
</headtags>
以下方法一直有效,直到最后一行,在查找属性值包含“og:”的元素时总是出错,显然有六个。冒号必须转义吗?我是这么认为的,但是删除它,该行在 Contains("og") 上仍然失败
public List<XElement> GetOpenGraphTagsForPage(string page)
{
var doc = XDocument.Load(_metaTagXmlFile);
var metaTags = doc.Descendants("headtags")
.Elements("tags")
//page value is modeldashboard
.Where(u => u.Attribute("page-path-from-root").Value.ToLower().Contains(page))
.Elements("tag") //[@type='meta'] didn't work in Xname to eliminate next line...why?
.Where(u => u.Attribute("type")?.Value == "meta")
.Where(u => u.Attribute("property").Value.Contains("og:"))
.ToList();
return metaTags;
}
另外,为什么不这样(错误说“[”字符是不允许的)
.Elements("tag[@type='meta']")
产生与此相同的结果
.Elements("tag") //[@type='meta'] didn't work in Xname to eliminate next line...why?
.Where(u => u.Attribute("type")?.Value == "meta")
第一个中的 Xpath 要求相同的东西