user1464139
user1464139

Reputation:

How can I use C# to create XML without a containing element?

I am using the following:

XElement select = new XElement("select");
XElement optGroup = null;

if (topics.Count() > 0) {
    optGroup = new XElement("optgroup", new XAttribute("label", "Admin"));
    optGroup.Add(new XElement("option", new XAttribute("value", "99"), new XText("Select Topic")));
    optGroup.Add(new XElement("option", new XAttribute("value", "00"), new XText("All Topics")));
    select.Add(optGroup);
    foreach (var topic in topics) {
        // skip root topic
        if (!topic.RowKey.EndsWith("0000")) {
            // optgroup
            if (topic.RowKey.EndsWith("00")) {
                optGroup = new XElement("optgroup", new XAttribute("label", topic.Title));
                select.Add(optGroup);
            }
                // option
            else if (optGroup != null) {
                optGroup.Add(new XElement("option", new XAttribute("value", topic.RowKey), new XText(topic.Title)));
            }
        }
    }
} else {
    optGroup = new XElement("optgroup", new XAttribute("label", "Admin"));
    optGroup.Add(new XElement("option", new XAttribute("value", "88"), new XText("No Topics")));
}                     
return (select.ToString());

It processes rows in a variable and uses the data to create a <select> ... </select> element for HTML.

It works however what I need is the contents of the <select> and not the opening <select> and closing </select> elements. Is there some way I could make this just return contents and not the outer <select> ?

Upvotes: 0

Views: 158

Answers (2)

Richard
Richard

Reputation: 109100

Add

using System.Xml.XPath;

to get access to the extension methods defined in the Extensions class in that namespace to get an XPathNavigator and its InnerXml property:

string inner = select.CreateNavigator().InnerXml;

Upvotes: 1

nunespascal
nunespascal

Reputation: 17724

Just trim what you don't want from the result.

return (select.ToString().Replace("<select>","").Replace("</select>",""));

Upvotes: 1

Related Questions