C# c、 在XML中更新子节点
我有一个如下所示的xml文件C# c、 在XML中更新子节点,c#,xml,linq,xelement,C#,Xml,Linq,Xelement,我有一个如下所示的xml文件 <ExecutionGraph> <If uniqKey="1"> <Do> <If uniqKey="6"> <Do /> <Else /> </If> </Do> <Else> <If uniqKey="2"> <Do />
<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>
现在elemenet有了整个标签,但我无法将我的任务插入到它的子项中
期望输出:
提前谢谢
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);
输出:
代码的输出不正确。你能告诉我你需要什么输出吗?我需要这个. 元素应该放在。。。element@Arash,我已经检查过了,它确实在Do中添加了任务。我不知道那里发生了什么。另外,您是否注意到.ElementDo选择DO子元素而不是元素本身?
var element = xGraph
.Descendants()
.Where(x => (string)x.Attribute("uniqKey") == parent.Key.ToString()).first();
<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>
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>