Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing newlines with XDocument

I'm populating a TreeView with nodes based on an XML document. However, it seems that when I go to put an attribute's value into a textbox, it loses it's newlines/carriage returns/tabs.

I start by adding a bunch of nodes with "task names". Each task has one or more queries in the XML document. Like so: <Tasks><Task name="aTaskName"><Queries><add Query="a long string with tabs and newlines and such" /></Queries></Task> ... </Tasks>

void PopulateQueries(XDocument doc, TreeView tree)
{
    foreach (TreeNode node in tree.Nodes)
    {
        var taskName = node.Text;
        var queriesNode = node.Nodes.Add("Queries");
        var queries = doc.Descendants("Tasks")
            .Descendants("Task")
            .Where(d => d.Attribute("name").Value == taskName)
            .Descendants("Queries")
            .Descendants("add")
            .ToList();

        for (int i = 0; i < queries.Count;i++)
        {
            queriesNode.Nodes.Add(queries[i].Attribute("Query").Value, "query" + i);
        }
    }
}

Later in a node click event:

void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    textBoxRaw.Text = string.Empty;
    if (e.Node.Text.StartsWith("query"))
    {
        textBoxRaw.Text = e.Node.Name;
    }
}

The Query attribute value contains a long SQL query with newlines, tabs, etc. But none of that seems to show up in the (multiline) text box, despite all my shouting at Visual Studio. What am I doing wrong? Also, var doc = XDocument.Load(filename, LoadOptions.PreserveWhitespace); doesn't seem to work either.

like image 369
Matthew Groves Avatar asked Aug 31 '11 21:08

Matthew Groves


1 Answers

XML processors must normalize attribute values by converting their whitespace characters (CR, LF, HT, etc) to a single space.

If you want to have values with such characters, you should consider having them as text nodes instead of attribute values.

like image 61
carlosfigueira Avatar answered Nov 05 '22 05:11

carlosfigueira