3

I'm creating a new XML Document that has some tags that have no innertext.

If I populate the innertext with some data then it works as needed in this instance, namely you get opening tag, innertext and closing tag all on one line:

<testtag>somevalue</testtag>

The problem arises with tags with no values. These need to be displayed in the same manner as above:

<testtag></testtag>

However, if I populate the innertext with an empty string it adds a carriage return & line feed which is not what the importing software needs.

<testtag>

</testtag>

If I leave innertext null then I get a self closing tag . Again this isn't as required.

I've tried removing /n and /r from innertext as some other posts have suggested but as soon as the document is saved the same issue occurs.

slikvik
  • 31
  • 1
  • 2
  • I have a similar issue and this seems to come from the XMLDocument.Save() method. Prior to save the attribute is empty as it should be without any CR/LF. – codea Sep 06 '16 at 17:22

1 Answers1

2

The following code does not suffer from the issue you describe. If this code sample does not put you on the right track please update your question with the code you are using so that we can better diagnose.

class Program
{
    static void Main(string[] args)
    {
        XmlWriterSettings settings = new XmlWriterSettings {Indent = true};
        XmlWriter writer = XmlWriter.Create("C:\\Users\\elaforc\\temp.xml", settings);

        XmlDocument xmlDocument = new XmlDocument();
        XmlElement parentElement = xmlDocument.CreateElement("Parent");
        XmlElement childElement = xmlDocument.CreateElement("Child");
        childElement.InnerText = "";
        parentElement.AppendChild(childElement);
        xmlDocument.AppendChild(parentElement);
        xmlDocument.Save(writer);
    }
}

Generates

<?xml version="1.0" encoding="utf-8"?>
<Parent>
   <Child></Child>
</Parent>
Eric LaForce
  • 2,125
  • 15
  • 24
  • I was hoping that worked for me as it seems like a perfectly valid answer! I have no clue why this thread went dead and this was never accepted as an answer! I have a similar issue here http://stackoverflow.com/questions/19258810 but mine has to do with LOADING an xml file not just creating a new one. – Arvo Bowen Oct 08 '13 at 21:32
  • The key point is the following line: XmlWriterSettings settings = new XmlWriterSettings {Indent = true}; – codea Sep 06 '16 at 17:25
  • @eric Is there a way to achieve the same without using the xmlWriterSettings? – Ishan Pandya May 13 '20 at 10:01