0

i am trying to create XML using C# and i am aware of the traditional method of creating XML such as

XmlDocument doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.InsertBefore(xmlDeclaration, doc.DocumentElement);

XmlElement element1 = doc.CreateElement("", "body", "");
doc.AppendChild(element1);

XmlElement element2 = doc.CreateElement("", "type", "");
element1.AppendChild(element2);

XmlElement element3 = doc.CreateElement("", "Numbers", "");
element2.AppendChild(element3);
XmlElement element4 = doc.CreateElement("", "one", "");
XmlText text1 = doc.CreateTextNode("1");
element4.AppendChild(text1);
element3.AppendChild(element4);

now i want the element to be list of XMLelement and the text as a list of XMLtext. i am having a problem to append the childnodes of the element while using the list.

 List<XmlElement> elements = new List<XmlElement>() {doc.CreateElement("", "type" ,""),doc.CreateElement("", "numbers" ,""),doc.CreateElement("", "one" ,""),doc.CreateElement("", "two" ,"") };

foreach (var elementss in elements)
{
    elementss.AppendChild(elementss);
    Console.WriteLine(elementss.ChildNodes);
}

please clarify whether i am right in implementing lists in this scenario..??? any help would be greatly appreciated.

2 Answers 2

2

Linq to XML, which is the name of what you are looking for, have a way of creating XML documents which can be better formatted than the older System.Xml way.

Maybe something like this could be easier to use:

var doc = new XElement("body", 
                  new XElement("type"),
                      new XElement("Numbers",
                          new XElement("one", 1)
                      )
                  )
              );
Sign up to request clarification or add additional context in comments.

2 Comments

thanks..i knew this earlier..i am trying to find an alternative to the conventional XmlDocument method..
Linq to XML is that alternative, unless you want to go with serialization.
0

i'm not quite sure why you add an item to itself in

elementss.AppendChild(elementss);

but, instead of adding new elements to the list, add the ones that exist:

foreach(XmlNode elements in doc.ChildNodes)
{
    Console.WriteLine(elementss.ChildNodes);
}

1 Comment

i am getting an error regarding the typecasting of variable to XMLNodeList

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.