【问题标题】:How to remove white spaces before xml nodes in C#如何在 C# 中删除 xml 节点之前的空格
【发布时间】:2016-03-09 10:14:27
【问题描述】:

谁能帮我解决如何删除 XML 标记之间的所有空格,如下所示:

<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

收件人:

<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body></note>

需要 xml 节点在不同的行中,但 xml 节点之前的空格不应该在那里

【问题讨论】:

  • 你为什么要这样做?它对您如何浏览节点没有影响。这可以通过 xpath 或 XMLStreamer 来完成。
  • 是的,正确但我有一个没有空格的旧 xml。为了与旧的 xml 进行比较,我们需要它。
  • 毫无意义。比较两个xml的正确方法是两个streamthrough每个元素并比较它们的元素和属性。一种被破解的方法是删除 > 和 stackoverflow.com/questions/4274524/…

标签: c# xml


【解决方案1】:

我相信 System.XML.Linq 中的 XDocument 类会为您做到这一点。 Save 和 ToString 方法都支持 SaveOptions 参数。将此设置为 None 应该会得到你想要的结果......

【讨论】:

    【解决方案2】:

    使用正则表达式

    如果您已将 xml 加载到字符串中,您可以尝试这样做,但我讨厌并且绝对不屑于正则表达式,所以我不能保证这会给您想要的。

    string x = " <Hello>text </Hello>   <itsAme>";
    string Replace1 = ">\\s+";
    string Replace2 = "\\s+<";
    
    x=Regex.Replace(x, Replace1 , ">");
    x=Regex.Replace(x, Replace2, "<");
    

    使用 XDocument

    我建议使用@Martin Milan 的答案。你可以这样做。但改为将 SaveOptions 设置为 DisableFormatting 以删除所有空格。并且应该给你一行,应该很容易与你的其他 xml 文件进行比较。

    string x = " <Hello>   <ItsAMe>  </ItsAMe>   </Hello>  ";
    XDocument xDoc = XDocument.Parse(x, LoadOptions.None);
    x = xDoc.ToString(SaveOptions.DisableFormatting);
    Console.WriteLine(x);
    

    【讨论】:

      【解决方案3】:

      你是用 XmlSerializer 写的吗?

      使用 XmlWriterSettings 指定 String.Empty 作为 IndentChars,您有多种选择;例如:

      XmlWriterSettings **ws** = new XmlWriterSettings();
      ws.CloseOutput = true;
      ws.Indent = true;
      ws.IndentChars = "";
      ws.OmitXmlDeclaration = true;
      ws.NewLineHandling = NewLineHandling.Entitize;
      ws.NewLineOnAttributes = false;
      

      将其写入文件...

      using (TextWriter writer = new StreamWriter(filename, false, Encoding.UTF8))
      {
          using (XmlWriter wr = XmlWriter.Create(writer, **ws**))
          {
              // Namespace?
              XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
              ns.Add("", "");
              serializer.Serialize(wr, o, ns);
          }
          writer.Close();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 2012-05-23
        • 2013-12-01
        • 1970-01-01
        相关资源
        最近更新 更多