Shruti
Shruti

Reputation: 39

How to remove white spaces before xml nodes in C#

could anyone please help me on how to remove all the white spaces between XML tags as shown below:

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

To:

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

Need xml nodes in different lines but spaces before xml nodes should not be there

Upvotes: 1

Views: 5938

Answers (3)

wizardgsz
wizardgsz

Reputation: 1

Do you write it using XmlSerializer?

Use XmlWriterSettings specifying String.Empty as IndentChars, you have several options; e.g.:

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

Writing it to file...

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();
}

Upvotes: 0

Kent Kostelac
Kent Kostelac

Reputation: 2446

Using Regex

If you have loaded your xml into a string you can try doing it this way, but I hate and have an absolute disdain for regex so I wont guarantee that this gives you what you want.

string x = " <Hello>text </Hello>   <itsAme>";
string Replace1 = ">\\s+";
string Replace2 = "\\s+<";

x=Regex.Replace(x, Replace1 , ">");
x=Regex.Replace(x, Replace2, "<");

Using XDocument

I recommend using @Martin Milan's answer. You can do it thusly. But instead set the SaveOptions to DisableFormatting to remove all whitespace. And should give you a single line, that should be easily comparable with your other xml file.

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

Upvotes: 3

Martin Milan
Martin Milan

Reputation: 6390

I believe the XDocument class from System.XML.Linq will do this for you. Both the Save and ToString method support a SaveOptions argument. Setting this to None should get you the results you're after...

Upvotes: 2

Related Questions