LINQ to XML:如何访问子节点

时间:2013-11-22 14:38:44

标签: c# xml linq linq-to-xml

我是LINQ to XML的新手,非常感谢获得子节点的帮助。

XML文档:

    <schedule>
    <job>
    <name>nativeJobExample</name>
    <group>nativeJobExampleGroup</group>
    <description>Sample job for Quartz Server</description>
    <job-type>Quartz.Job.NativeJob, Quartz</job-type>
    <job-data-map>
      <entry>
        <key>command</key>
        <value>native_job_example.bat</value>
      </entry>
      <entry>
        <key>consumeStreams</key>
        <value>true</value>
      </entry>
    </job-data-map>
  </job>
  <trigger>
    <simple>
      <name>nativeJobExampleSimpleTrigger</name>
      <group>nativeJobExampleSimpleTriggerGroup</group>
      <description>Simple trigger to simply fire sample job</description>
      <job-name>nativeJobExample</job-name>
      <job-group>nativeJobExampleGroup</job-group>
      <misfire-instruction>SmartPolicy</misfire-instruction>
      <repeat-count>5</repeat-count>
      <repeat-interval>10000</repeat-interval>
    </simple>
  </trigger>
</schedule>

我能够到达这样的节点:

XDocument document = XDocument.Load(@pmPathFileName);
XElement root = document.Root;
root.Elements("job").Where(e => e.Element("name").Value.Equals("nativeJobExample")).
Select(e => e.Element("description")).Single().SetValue("wwww");

XML文档包含多对作业和触发器。

有关如何更新值的两个问题:

  1. 如何获取job-data-map | entry | key | value?

  2. 如何触发| simple | name | repeat-count?

2 个答案:

答案 0 :(得分:1)

正如我在第一个案例中所理解的那样,您希望更新某些匹配的元素。你可以这样做:

        string key = "consumeStreams";
        string newValue = "false";
        var val1 = (
                       from jdm in document.Root.
                                            Elements("job").
                                            Elements("job-data-map").
                                            Elements("entry")
                       where jdm.Element("key") != null && jdm.Element("key").Value == key
                       select jdm.Element("value")
                   ).Single();

        val1.SetValue(newValue);

至于第二的情况。我宁愿使用更简洁的XPath语法,因为不需要匹配(从XML结构我可以看出只有一个元素)。

        var repeatCountElement = root.XPathSelectElement("/schedule/job/job-data-map/entry/key");
        if (repeatCountElement != null)
            repeatCountElement.SetValue("10");

答案 1 :(得分:0)

有多种方法可以做到这一点,最简单的方法就是使用XPathSelectElements:

var key = root.XPathSelectElements(“/ schedule / job / job-data-map / entry / key”);