下添加新的子節點是XML文檔在同級後代節點基於節點的子節點的屬性值
<al>
<hfs>
<hf id="1">A2</hf> ##1) based these hf nodes id attributes
<hf id="2">A1</hf>
</hfs>
<psteps>
<pstep>
<name>sharepoint</name>
<lze>
<lz hid="1"> ##1) in Lze node need to create same number lz nodes
## based previously quoted hf node id attribute
<ps>
<p>
<text>ziel</text>
<inhalt>ttt</inhalt>
</p>
<p>
<text></text>
<inhalt></inhalt>
</p>
</ps>
</lz>
<lz hid="2">
<ps>
<p>
<text></text>
<inhalt></inhalt> ##2) lz node with hid = "2" has 2 p nodes
</p>
<p>
<text></text>
<inhalt></inhalt>
</p>
</ps>
</lz>
</lze>
</pstep>
<pstep>
<name>aspnet</name>
<lze>
<lz hid="2"> ## 1)in Lze node need to create same number lz nodes
## based previously quoted hf node id attribute
<ps>
<p>
<text>ziel</text> ## 2)lz node with hid = "2" has 1 p node so need
<inhalt>ttt</inhalt> ## node to create 1 more as previously
</p> ## lz node
</ps>
</lz>
</lze>
</pstep>
</psteps>
</al>
我需要做兩件事情:基於HFS孩子HF
節點我需要創建hfs同胞psteps後代lze節點具有相同屬性值的lz節點的相同數量
接下來必須找到lz節點中具有相同最大數量的p個節點屬性值,並在具有相同屬性值的其餘lz節點中創建相同數量的p個節點。
這裏是我試圖產生示例XML:
<al>
<hfs>
<hf id="1">A2</hf>
<hf id="2">A1</hf>
</hfs>
<psteps>
<pstep>
<name>sharepoint</name>
<lze>
<lz hid="1">
<ps>
<p>
<text>ziel</text>
<inhalt>ttt</inhalt>
</p>
<p>
<text></text>
<inhalt></inhalt>
</p>
</ps>
</lz>
<lz hid="2">
<ps>
<p>
<text></text>
<inhalt></inhalt>
</p>
<p>
<text></text>
<inhalt></inhalt>
</p>
</ps>
</lz>
</lze>
</pstep>
<pstep>
<name>aspnet</name>
<lze>
<lz hid="2">
<ps>
<p>
<text>ziel</text>
<inhalt>ttt</inhalt>
</p>
<p>
<text></text>
<inhalt></inhalt>
</p>
</ps>
</lz>
<lz hid="1">
<ps>
<p>
<text></text>
<inhalt></inhalt>
</p>
<p>
<text></text>
<inhalt></inhalt>
</p>
</ps>
</lz>
</lze>
</pstep>
</psteps>
<al>
我用下面的代碼能夠創建<lz>
節點缺少的。我需要創建<p>
節點,我無法從每個<lz>
節點中選擇<p>
個節點。
var doc = XDocument.Load("XmlFile1.xml");
var hfIds = (from hf in doc.Descendants("hf")
from attr in hf.Attributes("Id")
select attr.Value).Distinct(StringComparer.Ordinal).ToList();
var lze2 = doc.Descendants("lze")
.Select(lze => new {
element = lze,
hfids = lze.Descendants("lz").Attributes("hid"),
paras = (from lz in lze.Elements("lz")
from ps in lz.Elements("ps")
from p in ps.Elements("p")
select p).ToList()
});
foreach (var c in lze2) {
foreach (var hfid in hfIds.Where(hfid => !c.hfids.Any(attr => hfid.Equals(attr.Value)))) {
c.element.Add(new XElement("lz", new XAttribute("hfid", hfid),
new XElement("ps",
new XElement("p"),
new XElement("Text"),
new XElement("Content"))));
break;
}
}
感謝您的幫助
嗨Sayad,謝謝你的幫助。您的代碼似乎不會選擇唯一的屬性 – gullamahi