开发者

XML DocumentWriter - Stop empty elements appearing over two lines in .NET

开发者 https://www.devze.com 2023-02-15 16:10 出处:网络
I am using the XML document object in VB.NET to manipulate XML. My application creates a new XML fragment and updates the XML via the innerXML method:

I am using the XML document object in VB.NET to manipulate XML.

My application creates a new XML fragment and updates the XML via the innerXML method:

reasonFrag.InnerXml = String.Format("<ReasonForPayment>{0}</ReasonForPayment>", reason)

This produces the correct XML output on most occasions, e.g.

<ReasonForPayment>reason</ReasonForPayment>

If the reason string is empty I get element spanning two lines in the XML as follows:

<ReasonForPayment>

</ReasonForPayment>

I am looking for a way of keeping the element on a single line while maintaining the same format, e.g.

&l开发者_JAVA百科t;ReasonForPayment></ReasonForPayment>

The alternative <ReasonForPayment /> is not acceptable (third party application wont accept it).

Thanks Steven


I think the best way to handle this would be to do something like this:

if (reason == null | reason.Trim() == "")
{
  reasonFrag.IsEmpty = true;
}
else
{
  reasonFrag.InnerText = reason.Trim();
}

This changes the output to

<ReasonForPayment/>


if(string.IsNullOrEmpty(reason))
{
   reasonFrag.InnerXml = "<ReasonForPayment></ReasonForPayment>"
}
else
{
   reasonFrag.InnerXml = String.Format("<ReasonForPayment>{0}</ReasonForPayment>", reason)
}


Not tested but maybe something like

edit threw it into LinqPad, works just fine for what you need.

public static string ToXmlFragment(this object input, string element)
{
    //extension method, place in a static class somewhere
    return string.IsNullOrEmpty(input.ToString()) ? 
        string.Format("<{0}></{0}>",element) :
        string.Format("<{0}>{1}</{0}>",element,input);
}


reasonFrag.InnerXml = reason.ToXmlFragment("ReasonForPayment");


The solution to my problem was unusual. When reading or writing files in .NET using streamreader/writer, textreader/writer and the XMLDocument object, the document format changes depending on the file extension. So for example reading a file with a XML extension, the file is treated and formatted as XML. This was causing my original problem, a empty element was output over two lines with a CRLF inserted. The solution was to output the steam to a file with a .txt extension and then rename the file to XML, then my formatting was preserved.

0

精彩评论

暂无评论...
验证码 换一张
取 消