0

I am generating an XML file using Xdocument,however,the code I am producing is not efficient(too much new objects in my code). I was wondering if you could tell me what parts of my code need to be changed.

 XDocument doc = new XDocument();

        foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("TEXTAREA"))
        {
            doc.Add(new XElement("Item", new XElement("GUID", el.Id), new XElement("Type",
                (el.GetAttribute("type").ToUpper())), new XElement("Title", el.GetAttribute("title")), new XElement("Name", el.Name),
                new XElement("Value", el.GetAttribute("value")), new XElement("MaxLength", el.GetAttribute("maxlength"))));                
            xmlcontents += Convert.ToString(doc.Document) + "\r\n";
        }

As you can see,I have used many new xElements. Is there any way to get rid of XElements?

2
  • What do you want to achieve? Do you want to build an XDocument in memory or do you simply need a string with XML markup? In the latter case I would suggest to use XmlWriter instead of XDocument, that should be more efficient. Commented May 8, 2013 at 10:03
  • @MartinHonnen:I need a XML string.Do you mean that I can use XMLWriter to generate an XML string? I would be grateful if you tell me how. Commented May 8, 2013 at 10:08

1 Answer 1

1

If you use an XmlWriter over a StringWriter you can use e.g.

string xml;

using (StringWriter sw = new StringWriter())
{
  using (XmlWriter xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }))
  {
    xw.WriteStartDocument();
    xw.WriteStartElement("Root");
    foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("TEXTAREA"))
    {
      xw.WriteStartElement("Item");
      xw.WriteElementString("GUID", el.Id);
      xw.WriteElementString("Type", el.GetAttribute("type").ToUpper());
      // write further elements the same way
      xw.WriteEndElement();
    }
    xw.WriteEndElement();
    xw.WriteEndDocument();
  }
  xml = sw.ToString();
}
Sign up to request clarification or add additional context in comments.

Comments

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.