我有一个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>
进入<Do>
标签。
无论我尝试什么,都是以下c#代码。
var element = xGraph
.Descendants()
.Where(x => (string)x.Attribute("uniqKey") == parent.Key.ToString()).first();
现在elemenet
有完整标记但我无法将我的任务插入其<DO>
孩子。
期望输出:
<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>
提前致谢。
答案 0 :(得分: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>