如何使用两个名称空间为xml编写xpath?

时间:2018-04-16 11:45:06

标签: c# xml xpath xml-namespaces

我正在尝试获取标题的值以及与属性等于备用的链接。但是使用命名空间,我发现获取值有点挑战。

我添加了我的命名空间,如下所示,但我的结果是使用Enumeration返回,结果没有结果:

a

我正在使用带有linq和xpath混合的XDocument来查询我的数据。

我使用XPath如下:

nameSpaceManager_ = new XmlNamespaceManager(new NameTable());
nameSpaceManager_.AddNamespace("viz", "http://www.vizrt.com/atom");
nameSpaceManager_.AddNamespace("atom", "http://www.w3.org/2005/Atom");

更新

XML:

var showName = showNode.XPathEvaluate("/atom:entry/atom:title/text()", nameSpaceManager_);

更新了查询

<?xml version="1.0" encoding="UTF-8"?>
<feed xml:base="http://127.0.0.1:8580/directory/shows/" xmlns="http://www.w3.org/2005/Atom">
    <entry xmlns="http://www.w3.org/2005/Atom" 
    xmlns:viz="http://www.vizrt.com/atom">
        <title>My Show</title>
        <author>
            <name>Media Sequencer</name>
        </author>
        <id>tag:user,2017-02-03:0:/directory/shows/My%20Show.show</id>
        <updated>2017-02-03T11:41:05Z</updated>
        <summary>Show My Show</summary>
        <category scheme="http://www.vizrt.com/types" term="directory" />
        <category scheme="http://www.vizrt.com/types" term="show" />
        <category scheme="http://www.vizrt.com/types" term="trio_4_layer_collection" label="Trio 4 Layer Collection" />
        <link type="application/atom+xml;type=feed" rel="alternate" href="http://127.0.0.1:8580/show/%7B4575C71F-FC79-4813-A92F-D6297D5C517C%7D/" />
        <link type="application/atom+xml;type=entry" rel="self" href="http://127.0.0.1:8580/directory/shows/My%20Show.show" />
        <viz:empty>false</viz:empty>
    </entry>
    <entry xmlns="http://www.w3.org/2005/Atom" 
    xmlns:viz="http://www.vizrt.com/atom">
        <title>My Show 2</title>
        <author>
            <name>Media Sequencer</name>
        </author>
        <id>tag:user,2017-02-03:0:/directory/shows/My%20Show.show</id>
        <updated>2017-02-03T11:41:05Z</updated>
        <summary>Show My Show</summary>
        <category scheme="http://www.vizrt.com/types" term="directory" />
        <category scheme="http://www.vizrt.com/types" term="show" />
        <category scheme="http://www.vizrt.com/types" term="trio_4_layer_collection" label="Trio 4 Layer Collection" />
        <link type="application/atom+xml;type=feed" rel="alternate" href="http://127.0.0.1:8580/show/%7B4575C71F-FC79-4813-A92F-D6297D5C517C%7D/" />
        <link type="application/atom+xml;type=entry" rel="self" href="http://127.0.0.1:8580/directory/shows/My%20Show.show" />
        <viz:empty>false</viz:empty>
    </entry>
</feed>

1 个答案:

答案 0 :(得分:0)

你做的几乎一切都正确。

只需使用XPathSelectElement代替XPathEvaluate

var showName = showNode.XPathSelectElement("/atom:entry/atom:title", nameSpaceManager_).Value;

var linkTypes = showNode.XPathSelectElements("/atom:entry/atom:link[@rel='alternate']", nameSpaceManager_)
    .Select(e => e.Attribute("type").Value);