0

我有一个 xml 文件,其中有两个链接。如果它确实获得了它的 href 值,我需要检查是否存在与 rel next 的链接。

<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/" />
4

2 回答 2

2

如何将 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-08T15:04:38.673 回答
0

You can use this public xml library and then get the value with:

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 ...

That should work with the a:link, but if it doesn't try it without the a:. It would depend on where a's namespace was declared. If it is in the root node it should be fine.

XGetElement() is basically a combination of XPathElement("//a:link[@rel={0}]").Get<string>("href", null). Get() also being a part of the library for getting values from nodes, checking first for an attribute by the name and then for a child node.

于 2012-06-08T15:30:34.733 回答