【问题标题】:Preserve white space and new lines in xdocument在 xdocument 中保留空白和新行
【发布时间】:2021-12-07 13:18:56
【问题描述】:

我有一个看起来像这样的 xml 文件,

问题)当我通过 XDcoument 加载文档时,如何在加载文档时保留所有空格和换行符。 LoadOptions.PreseveWhitesapce 不起作用

谢谢。

 <!--
********************************************************
 header
********************************************************
    -->
   <!--sample -->
   <realmCode
      code="US"/>
   
   <!-- sample -->
   <typeId
      root="2.16.840.1.113883.1.3"
      extension="samo"/>
   
   <!-- sample -->
   <!-- sample -->
   <templateId
      root="2.16.840.1.113883.10.20.22.1.1"/>
   <!-- *** formatting. *** -->
   <!-- formatting -->
   <templateId
      root="2.16.840.1.113883.10.20.22.1.2"/>
   
   <!-- formatting -->
   <id`
      extension="samo"
      root="1.1.1.1.1.1.1.1.1"/>
   
   <!--formatting -->"

【问题讨论】:

  • “不起作用”不足以弄清楚到底发生了什么 - 请查看 minimal reproducible example 关于发布调试问题代码的指导并进行相应的编辑。
  • 请详细说明您面临的问题。 “不起作用”是什么意思?你有什么具体的错误吗?
  • 感谢您的回复,是的,我的示例并不完整,只是为了让您了解我所面临的问题。我的问题是我需要保留空格和换行符,因为我需要捕获原始文件的确切行号。

标签: c# xml linq-to-xml xmldocument


【解决方案1】:

您的 XML 示例很少有问题,应该在解析 XML 之前“修复”:

  1. 缺少根元素。它可以在解析您的示例之前手动添加。
  2. 重音字符无效(`,位于“
  3. 没有目的的尾随双引号。
  4. 换行符(不影响解析,但也应该修复)。空格一点也不麻烦。

所以,要解决所有问题,首先您应该使用System.IO.File.ReadAllText 将 XML 文件读取为简单的单个字符串。然后,您可以使用 System.Text.RegularExpressions 命名空间中的 Regex 类及其方法 Replace() 与模式“@”[`\r\n]“”删除换行符和无效的重音符号@987654327 @Trim` 方法。

由于您的 XML 示例没有根元素,当您尝试 Parse 时会导致 System.Xml.XmlExceptionMissing root element 消息,我们手动添加它并连接一些根标签:"&lt;root&gt;" + fixedXmlString + "&lt;/root&gt;"

整段代码如下所示:

static void Main()
{
    // Reading XML file as string.
    // Replacing invalid grave accent ` 
    // Replacing line breaks
    // Trimming trailing double quote
    var xmlString = Regex.Replace(File.ReadAllText("example.xml"), @"[`\r\n]", "").Trim('\"');

    // Adding some root element as it doesn't exists in example
    xmlString = "<root>" + xmlString + "</root>";

    // Now it parsable
    XDocument xDoc = XDocument.Parse(xmlString);

    // Save as correct one
    xDoc.Save("example_fixed.xml");
}

输出(.Save() 之后)如下所示:

【讨论】:

  • 感谢您的回复,是的,我的示例并不完整,只是为了让您了解我所面临的问题。我的问题是我需要保留空格和换行符,因为我需要捕获原始文件的确切行号。
  • “原始文件的确切行号”?你的意思是像普通文本一样解析XML?真的确定这是个好方法吗?
  • 我们有一个特定的业务案例,我们需要在其中显示上传文件的行号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多