我有一个xml文件,其中有两个链接。我需要检查下一个与rel的链接是否存在,如果它确实获得了它的href值。
<a:link rel="prev" type="application/atom+xml" type="application/atom+xml" href="/v3.2/en-us/" />
<a:link rel="next" type="application/atom+xml" type="application/atom+xml" href="/v3.2/en-us/" />发布于 2012-06-08 23:04:39
如何将xml读入XDocument并使用LINQ查找下一个元素。
XDocument x = XDocument.Parse("<xml><link rel=\"prev\" type=\"application/atom+xml\" href=\"/v3.2/en-us/\" /> <link rel=\"next\" type=\"application/atom+xml\" href=\"/v3.2/en-us/\" /></xml>");
XElement link = x.Descendants("link")
.FirstOrDefault(a => a.Attribute("rel").Value == "next");
String href = string.Empty;
if(link != null)
{
href = link.Attribute("href").Value;
}发布于 2012-06-08 23:30:35
您可以使用this public xml library,然后使用以下命令获取值:
XElement root = XElement.Load(file); // or .Parse(string)
string href = root.XGetElement<string>("//a:link[@rel={0}]/href", null, "next");
if(null != href)
... link was found ...这应该适用于a:link,但如果它不能在没有a:的情况下尝试它的话。这将取决于a的命名空间是在哪里声明的。如果它在根节点中,应该没问题。
XGetElement()基本上是XPathElement("//a:link[@rel={0}]").Get<string>("href", null)的组合。Get()也是用于从节点获取值的库的一部分,它首先通过名称检查属性,然后检查子节点。
https://stackoverflow.com/questions/10951052
复制相似问题