Harry89pl
Harry89pl

Reputation: 2435

Building xml from scratch and getting result in string?

I'm trying to build up xml document from scratch with use linq-to-xml.

XElement root = new XElement("RootNode");
            XDocument doc = new XDocument(
            new XDeclaration("1.0", "utf-8", ""), root
            );
            for (int j = 0; j < 10; j++)
            {
                XElement element = new XElement("SetGrid");
                element.SetElementValue("ID", j);                    
                root.Add(element);

            }
   var reader = doc.CreateReader();//doc has 10 elements inside root element
   string result = reader.ReadInnerXml();//always empty string

How can I get string from XDocument?

Upvotes: 1

Views: 389

Answers (4)

4b0
4b0

Reputation: 22323

One option for empty string as per documentation.

XmlReader return:

All the XML content, including markup, in the current node. If the current node has no children, an empty string is returned. If the current node is neither an element nor attribute, an empty string is returned.

try:

XmlReader reader = doc.CreateReader();
reader.Read(); 
string result = reader.ReadInnerXml()

Upvotes: 1

Eddy Shterenberg
Eddy Shterenberg

Reputation: 199

There's a full answer is here.

Long story short, you're missing reader.MoveToContent();

i.e. it should be:

var reader = root.CreateReader();
reader.MoveToContent(); // <- the missing line
string result = reader.ReadInnerXml();

This way the result won't be empty and you even don't have to create XDocument

So the full code from the original question + the fix is:

XElement root = new XElement("RootNode");
for (int j = 0; j < 10; j++)
{
    XElement element = new XElement("SetGrid");
    element.SetElementValue("ID", j);
    root.Add(element);
}

var reader = root.CreateReader();// root has 10 elements
reader.MoveToContent(); // <-- missing line
string result = reader.ReadOuterXml(); // now it returns non-empty string

Output:

<RootNode><SetGrid><ID>0</ID></SetGrid><SetGrid><ID>1</ID></SetGrid><SetGrid><ID>2</ID></SetGrid><SetGrid><ID>3</ID></SetGrid><SetGrid><ID>4</ID></SetGrid><SetGrid><ID>5</ID></SetGrid><SetGrid><ID>6</ID></SetGrid><SetGrid><ID>7</ID></SetGrid><SetGrid><ID>8</ID></SetGrid><SetGrid><ID>9</ID></SetGrid></RootNode>

Note: The code is tested in Visual Studio 2013 / .NET Framework 4.5

MDSN Reference: XmlReader.ReadOuterXml

Upvotes: 0

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

var wr = new StringWriter();
doc.Save(wr);
var xmlString = wr.GetStringBuilder().ToString());

Upvotes: 0

I4V
I4V

Reputation: 35363

Just use string result = doc.ToString() or

var wr = new StringWriter();
doc.Save(wr);
string result = wr.ToString();

Upvotes: 2

Related Questions