使用Xdocument按名称获取xml元素的值

时间:2013-04-17 16:23:38

标签: xml linq-to-xml

我有以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="430" pid="45202118763477" sid="">
    <lastmodified timestamp="1366113600000">
        Tue, 16 Apr 2013 12:00:00 +0000
    </lastmodified>
    <links/>
    <keywords/>
    <slides/>
    <copyright>
        Copyright owned by original broadcaster
    </copyright>
    <title>
        BBC News
    </title>
    <comment>
        The latest news updates from around the world.
    </comment>
    <author>
        BBC World Sv_
    </author>
    <email/>
    <captioning/>
    <extendeddata>
        <data name="keepOriginal">
            0
        </data>
        <data name="keepTranscoded">
            0
        </data>
        <data name="realStartTime">
            1366113604
        </data>
        <data name="scheduledStartTime">
            1366113600
        </data>
        <data name="broadcastLength">
            360
        </data>
        <data name="broadcastChannel">
            BBC World Sv_
        </data>
        <data name="paddingUsed">
            0
        </data>
        <data name="transcodingSpec"/>
        <data name="transcoding">
            succeeded
        </data>
        <data name="transcodingProfile">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast &quot;-l 270 -b 400 -R 48 -B 64&quot; --keep-files true
        </data>
        <data name="transcoderDetails">
            ver 1.58.2.5, 2013-04-16  13:08:08 up 42 days, 12:00,  0 users,  load average: 0.35, 0.13, 0.07, OS20031 212.70.71.204
        </data>
        <data name="originalFilename">
            /var/lib/etvd/mpegts/BBC World Sv_/BBC News (16-Apr-2013 13.00).emcast
        </data>
        <data name="originalRecordingTime">
            created 2013-04-16 , last modified 2013-04-16 : recording lasted 0s
        </data>
        <data name="primaryFormat">
            mp4
        </data>
        <data name="doXml">
            True
        </data>
        <data name="doFiles">
            True
        </data>
    </extendeddata>
    <categories>
        <category name="em:podcast">
            mp4
        </category>
    </categories>
</video>

使用XDocument,我可以进入<extendeddata>罚款的后代,返回所有数据节点和值但是如何根据数据属性的名称专门获取值1?所以例如我想进入一个特定的元素,例如:<data-name="realStartTime">1366113604</data>是1366113604作为我想要的价值。

干杯

2 个答案:

答案 0 :(得分:1)

您需要基本上过滤所需的元素。调用Descendants后,您就拥有了一系列元素,您需要对具有属性name并且值为realStartTime的元素进行过滤。这是实现这一目标的一种方法:

var realStartTime =
    xdoc.Descendants("data")
        .Single(x => x.Attribute("name").Value == "realStartTime")
        .Value
        .Trim();

realStartTime的值将为1366113604

答案 1 :(得分:0)

获得extendeddata元素后,您需要过滤data属性上的子name元素,如下所示

var doc = XDocument.Parse(...);

var result = doc.Descendants("extendeddata")
    .Elements()
    .Single(x => x.Attribute("name") != null && x.Attribute("name").Value == "realStartTime")
    .Value;