开发者

XmlElement with empty string parsed incorrect

I'm working on a project where an object is parsed as an XmlDocument and sent to a service. All appears to be working properly. There is however a problem with empty parameters.

When a parameter is filled with an empty string ("" or string.Empty), the following XmlElement is parsed:

<parameterName></parameterName>

I need it to be parsed like this:

<parameterName />

I'm told this has always worked like this until we migrated this project from .NET 1.1 to .NET 2.0. I thought it would be logical an empty element would be parsed like <parameterName/>. But it appears it doesn't.

The code used to parse the parameter to XML is this:

public override XmlNode GetXml(XmlNode parentNode)
{
    if (!Assigned) return null;
    XmlElement node = parentNode.OwnerDocument.CreateElement(Name);
    parentNode.AppendChild(node);
    node.InnerText = Value.ToString();
    return node;
}

This doesn't appear to be very strange, just creating an element with an empty value. All parameters of this object are parsed with this method and put inside a big XmlDocument. When checking out the XmlDocument.OuterXml I can see the elements are parsed 'incorrect'.

Is there an easy way I can change this behaviour. When 开发者_如何学JAVAsearching through the code history in TFS I can't see any significant changes in the code which would result in this incorrect parsing. The only massive change which was done is changing the .NET framework version (1.1 to 2.0) and changed the project from being a .NET 1.1 webservice to a .NET 2.0 class library.


Set the IsEmpty property to true on your element:

public override XmlNode GetXml(XmlNode parentNode)
{
    if (!Assigned) return null;
    XmlElement node = parentNode.OwnerDocument.CreateElement(Name);
    parentNode.AppendChild(node);
    node.InnerText = Value.ToString();
    node.IsEmpty = string.IsNullOrEmpty(node.InnerText);
    return node;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜