tags:

views:

711

answers:

1

Is it possible to select a node using an XPathNodeIterator and get the Outer Or InnerXML without indentation?

Since the results are used in XHTML output the indentation (using spaces) will result in layout differences.

Sample code snippet:

xmlDoc = New XPathDocument(fileIn, xmlSpace.Preserve)
xmlNav = xmlDoc.CreateNavigator()
Dim xmlNode As XPathNodeIterator

xmlNode = xmlNav.Select("/books/chapter[page[@process='True']]")
    While xmlNode.MoveNext()

     content = xmlNode.Current.selectSingleNode("para").OuterXML)
etc.

In this case i would get the following result (note that the original document (fileIn) has no identation and XML is all just one a single line:

<para process="True">
  <a href="#1109062">
    <em>Some content</em>
  </a>
</para>

I would like to get the following.

<para process="True"><a href="#1109062"><em>Some content</em></a></para>
+2  A: 

Reflector suggests there's no quick setting to change here. This is the source of XPathNavigator.get_OuterXml :

public virtual string get_OuterXml()
{
    if (this.NodeType == XPathNodeType.Attribute)
    {
        return (this.Name + "=\"" + this.Value + "\"");
    }
    if (this.NodeType == XPathNodeType.Namespace)
    {
        if (this.LocalName.Length == 0)
        {
            return ("xmlns=\"" + this.Value + "\"");
        }
        return ("xmlns:" + this.LocalName + "=\"" + this.Value + "\"");
    }
    StringWriter output = new StringWriter(CultureInfo.InvariantCulture);
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = true;
    settings.ConformanceLevel = ConformanceLevel.Auto;
    XmlWriter writer2 = XmlWriter.Create(output, settings);
    try
    {
        writer2.WriteNode(this, true);
    }
    finally
    {
        writer2.Close();
    }
    return output.ToString();
}

Note the settings.Indent = true.

One idea would be to create a helper method that does what this code does, but using your preferred settings for the XmlWriter. Then call this method with the node you find, rather than accessing its OuterXml.

AakashM
Thanks it worked. I created a small helper function that outputs the "plain" XML based on the XPathNavigator.get_OuterXml source.
barry