如何保持回车解析XML

Bap*_*ptX 8 c# xml linq linq-to-xml c#-4.0

我在互联网上看如何保持从XML数据回车,但我找不到答案,所以我在这里:)

目标是在文件中写入XML数据的内容.因此,如果节点的值包含一些"\ r \n"数据,则软件需要在文件中写入它们以创建新行,但它不会写入,即使有空格:保留.

这是我的测试类:

XElement xRootNode = new XElement("DOCS");
XElement xData = null;

//XNamespace ns = XNamespace.Xml;
//XAttribute spacePreserve = new XAttribute(ns+"space", "preserve");
//xRootNode.Add(spacePreserve);

xData = new XElement("DOC");
xData.Add(new XAttribute("FILENAME", "c:\\titi\\prout.txt"));
xData.Add(new XAttribute("MODE", "APPEND"));
xData.Add("Hi my name is Baptiste\r\nI'm a lazy boy");

xRootNode.Add(xData);

bool result = Tools.writeToFile(xRootNode.ToString());
Run Code Online (Sandbox Code Playgroud)

这是我的流程类:

try
{
    XElement xRootNode = XElement.Parse(xmlInputFiles);
    String filename = xRootNode.Element(xNodeDoc).Attribute(xAttributeFilename).Value.ToString();
    Boolean mode = false;
    try
    {
         mode = xRootNode.Element(xNodeDoc).Attribute(xWriteMode).Value.ToString().ToUpper().Equals(xWriteModeAppend);
    }
    catch (Exception e)
    {
         mode = false;
    }

    String value = xRootNode.Element(xNodeDoc).Value;
    StreamWriter destFile = new StreamWriter(filename, mode, System.Text.Encoding.Unicode);

    destFile.Write(value);
    destFile.Close();

    return true;
}
catch (Exception e)
{
    return false;
}
Run Code Online (Sandbox Code Playgroud)

有人有想法吗?

Mar*_*nen 4

如果您想在保存 a 时保留元素或属性内容中的 cr lf ,XDocument或者XElement您可以通过使用某些方法来实现XmlWriterSettings,即NewLineHandlingEntitize:

        string fileName = "XmlOuputTest1.xml";

        string attValue = "Line1.\r\nLine2.";
        string elementValue = "Line1.\r\nLine2.\r\nLine3.";

        XmlWriterSettings xws = new XmlWriterSettings();
        xws.NewLineHandling = NewLineHandling.Entitize;

        XDocument doc = new XDocument(new XElement("root",
                                      new XAttribute("test", attValue),
                                      elementValue));

        using (XmlWriter xw = XmlWriter.Create(fileName, xws))
        {
            doc.Save(xw);
        }

        doc = XDocument.Load(fileName);
        Console.WriteLine("att value: {0}; element value: {1}.",
                           attValue == doc.Root.Attribute("test").Value,
                           elementValue == doc.Root.Value);
Run Code Online (Sandbox Code Playgroud)

在该示例中,该值在保存和加载的往返过程中被保留,因为样本的输出是“att value:True;element value:True”。