【问题标题】:c#, update child node in XMLc#,更新XML中的子节点
【发布时间】:2018-05-16 04:49:55
【问题描述】:

我有一个如下所示的 xml 文件

<ExecutionGraph>
  <If uniqKey="1">
    <Do>
      <If uniqKey="6">
        <Do />
        <Else />
      </If>
    </Do>
    <Else>
      <If uniqKey="2">
        <Do />
        <Else>
          <If uniqKey="3">
            <Do />
            <Else />
          </If>
        </Else>
      </If>
    </Else>
  </If>
</ExecutionGraph>

现在我想找到 uniqKey=3 并插入

<Task id="3" xmlns="urn:workflow-schema">
  <Parent id="-1" />
</Task>

进入其&lt;Do&gt; 标签。

我尝试的是下面的 c# 代码。

var element = xGraph
    .Descendants()
    .Where(x => (string)x.Attribute("uniqKey") == parent.Key.ToString()).first();

现在elemenet 有整个标签,但我无法将我的任务插入到它的&lt;DO&gt; 孩子中。

所需的输出:

<ExecutionGraph>
<If uniqKey="1">
    <Do>
        <If uniqKey="6">
            <Do />
            <Else />
        </If>
    </Do>
    <Else>
        <If uniqKey="2">
            <Do />
            <Else>
                <If uniqKey="3">
                    <Do>
                        <Task id="3"
                            xmlns="urn:workflow-schema">
                            <Parent id="-1" />
                        </Task>
                    </Do>
                    <Else />
                </If>
            </Else>
        </If>
    </Else>
</If>

提前致谢。

【问题讨论】:

    标签: c# xml linq xelement


    【解决方案1】:
    string str = "<ExecutionGraph><If uniqKey='1'><Do><If uniqKey='6'><Do /><Else /></If></Do><Else><If uniqKey='2'><Do /><Else><If uniqKey='3'><Do /><Else /></If></Else></If></Else></If></ExecutionGraph>";
                XDocument doc = XDocument.Parse(str);
                var element = doc
                                .Descendants()
                                .Where(x => (string)x.Attribute("uniqKey") == "3").FirstOrDefault().Element("Do");
                XElement task = XElement.Parse("<Task id='3' xmlns='urn:workflow-schema'><Parent id='-1' /></Task>");
                element.Add(task);
    

    输出:

    <If uniqKey="3">
                <Do>
                  <Task id="3" xmlns="urn:workflow-schema">
                    <Parent id="-1" />
                  </Task>
                </Do>
                <Else />
              </If>
    

    【讨论】:

    • 您的代码输出不正确。它的
    • 你能告诉我你需要什么输出吗?
    • 我需要这个。 做>
    • 元素应该放在 ... 元素内
    • @Arash,我已经检查过了,它确实在Do 中添加了任务。我不确定那里发生了什么。另外,您是否注意到 .Element("Do") 选择 DO 子节点而不是元素本身?
    猜你喜欢
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多