Мне известно о совете, предоставленном здесь
но, тем не менее, мне нужна помощь, чтобы понять, что в моем коде не так.
У меня есть список объектов, полученных из этого класса
public class Leaf
{
public String key { get; set; }
public String id { get; set; }
public String value { get; set; }
public List<Leaf> branch { get; set; } //children
public Leaf()
{
branch = new List<Leaf>();
key = "";
id = "";
value = "";
parent_id_value = "";
}
}
В основном у меня есть эти объекты:
List<Leaf> tree = new List<Leaf>();
XElement xmloutput = new XElement("root");
Теперь я хотел бы пройтись по своему списку и его дочерним элементам, чтобы создать вложенную структуру XML, используя следующие правила:
- Когда у объекта Leaf нет дочерних элементов, процедура должна создать элемент
<dictionaryitem/>
. - Когда у листа есть дочерние элементы, процедура должна создать
<dictionarygroup></dictionarygroup>
, который содержит дочерние элементы, которые являются либо элементом словаря, либо группой словарей, в зависимости от того, есть ли у них сами дочерние элементы или нет. - И DictionaryItem, и DictionGroup имеют одинаковые атрибуты, производные от объекта Leaf.
Моя рекурсивная процедура выглядит следующим образом:
public static XElement CreateString(List<Leaf> tree, XElement xmloutput)
{
XElement xml = null;
foreach(Leaf lf in tree)
{
if(lf.branch.Count > 0 && lf.branch[0].id!="")
{
xml = new XElement("dictionarygroup",
new XAttribute("codeScheme", 1),
new XAttribute("codeValue", lf.id),
new XAttribute("codeMeaning", lf.value),
new XAttribute("codeSchemeVersion", "01"),
new XAttribute("isCancelled", "false"),
new XElement(CreateString(lf.branch, null))
);
}
else
{
xml = new XElement("dictionaryItem",
new XAttribute("codeScheme", 1),
new XAttribute("codeValue", lf.id),
new XAttribute("codeMeaning", lf.value),
new XAttribute("codeSchemeVersion", "01"),
new XAttribute("isCancelled", "false")
);
}
if (xmloutput != null)
xmloutput.Add(xml);
else
xmloutput = xml;
xml = null;
}
return xmloutput;
}
Он дает результат, но не ожидаемый; давайте рассмотрим эти данные в качестве примера:
List<Leaf> tree = new List<Leaf>();
Leaf leaf1 = new Leaf();
leaf1.key = "L1";
leaf1.id = "257170";
leaf1.value = "house";
Leaf leaf2 = new Leaf();
leaf2.key = "L1";
leaf2.id = "44444";
leaf2.value = "mouse";
Leaf leaf1_1 = new Leaf();
leaf1_1.key = "L2";
leaf1_1.id = "323233";
leaf1_1.value = "window";
Leaf leaf1_2 = new Leaf();
leaf1_2.key = "L2";
leaf1_2.id = "666666";
leaf1_2.value = "door";
leaf1.branch.Add(leaf1_1);
leaf1.branch.Add(leaf1_2);
tree.Add(leaf1);
tree.Add(leaf2);
Я ожидаю следующего результата:
<root>
<dictionarygroup codeScheme="1" codeValue="257170" codeMeaning="house" codeSchemeVersion="01" isCancelled="false">
<dictionaryItem codeScheme="1" codeValue="323233" codeMeaning="window" codeSchemeVersion="01" isCancelled="false" />
<dictionaryItem codeScheme="1" codeValue="666666" codeMeaning="door" codeSchemeVersion="01" isCancelled="false" />
</dictionarygroup>
<dictionaryItem codeScheme="1" codeValue="44444" codeMeaning="mouse" codeSchemeVersion="01" isCancelled="false" />
Instead I get this:
<root>
<dictionarygroup codeScheme="1" codeValue="257170" codeMeaning="house" codeSchemeVersion="01" isCancelled="false">
<dictionaryItem codeScheme="1" codeValue="323233" codeMeaning="window" codeSchemeVersion="01" isCancelled="false">
<dictionaryItem codeScheme="1" codeValue="666666" codeMeaning="door" codeSchemeVersion="01" isCancelled="false" />
</dictionaryItem>
</dictionarygroup>
<dictionaryItem codeScheme="1" codeValue="44444" codeMeaning="mouse" codeSchemeVersion="01" isCancelled="false" />
So everytime there are children the first is used as a grouping tag that contains the other siblings, so it acts like a parent.