开发者

LINQ to XML generates \r\n between tags?

开发者 https://www.devze.com 2023-01-15 08:39 出处:网络
I am generating a XElement having this structure: <TestNames>\\r\\n <Test>YA</Test>\\r\\n <Test>YO</Test>\\r\\n </TestNames>

I am generating a XElement having this structure:

<TestNames>\r\n <Test>YA</Test>\r\n <Test>YO</Test>\r\n </TestNames>

How do I get rid of the whitespaces and \r\n in a non-hack way :)

Update:

XElement tests开发者_运维问答XmlDocument= new XElement("TestNames");           

foreach (string test in selectedTests)         
    testsXmlDocument.Add(new XElement("Test",test)); 

return testsXmlDocument.ToString();


XElement provides an overload of ToString that takes an argument of type SaveOptions. One of the values of this enumeration is DisableFormatting.

If this doesn't give you enough control then you need to use the Save overload of XElement that takes an instance of XmlWriter. The output of an XmlWriter can be controlled by using XmlWriterSettings.

Note that the recommended way of creating an XmlWriter is to use the static Create method instead of constructing one directly. If you wantthe output in a string, you can use the overload that takes a StringWriter.


I had to write database data to an xml file and read it back from the xml file, using LINQ to XML. Some fields in a record were themselves xml strings complete with \r characters. These had to remain intact. I spent days trying to find something that would work, but it seems Microsoft was by design converting \r to \n.

The following solution works for me:

To write a loaded XDocument to the XML file keeping \r intact, where xDoc is an XDocument and filePath is a string:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings 
    { NewLineHandling = NewLineHandling.None, Indent = true };
using (XmlWriter xmlWriter = XmlWriter.Create(filePath, xmlWriterSettings))
{
    xDoc.Save(xmlWriter);
    xmlWriter.Flush();
}

To read an XML file into an XElement keeping \r intact:

using (XmlTextReader xmlTextReader = new XmlTextReader(filePath) 
   { WhitespaceHandling = WhitespaceHandling.Significant })
{
     xmlTextReader.MoveToContent();
     xDatabaseElement = XElement.Load(xmlTextReader);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号