开发者

How to output XmlDocument so that element attributes are indented as well?

I want to output XmlDocument so that the attributes are indented as well. I tried two approaches:

var cfgXmlDoc = new XmlDocument();
cfgXmlDoc.PreserveWhitespace = true;
cfgXmlDoc.Load(cfgFilePath);
...
File.WriteAllText(cfgFilePath, cfgXmlDoc.OuterXml);

AND

var cfgXmlDoc = new XmlDocument();
cfgXmlDoc.Load(cfgFilePath);
...
using (var xmlWriter = new XmlTextWriter(cfgFilePath, Encoding.UTF8))
{
  xmlWriter.Formatting = Formatting.Indented;
  cfgXmlDoc.WriteTo(xmlWriter);
}

As expected, none indent the attributes. Does anyone know how to do it?

Thanks.

EDIT1

For instance, consider this piece of a XML:

  <dataPortalProxies thisEndpointKind="Agent">
    <data开发者_开发问答PortalProxy isEnabled="true" name="NC Server" endpointKind="Server"
                     implementation="Shunra.Common.Csla.WcfOneWayProxy, Shunra.Common">
      <add key="AddressTemplate" value="net.msmq://{0}/private/nc_queue"/>
    </dataPortalProxy>
    <dataPortalProxy isEnabled="true" name="Peer Agent" endpointKind="Agent"
                     implementation="Shunra.Common.Csla.WcfDynamicProxy, Shunra.Common">
      <add key="AddressTemplate" value="https://{0}:7000/NCAgent/WcfPortal.svc"/>
    </dataPortalProxy>
  </dataPortalProxies>

Putting it through the XmlDocument yields this result:

  <dataPortalProxies thisEndpointKind="Agent">
    <dataPortalProxy isEnabled="true" name="NC Server" endpointKind="Server" implementation="Shunra.Common.Csla.WcfOneWayProxy, Shunra.Common">
      <add key="AddressTemplate" value="net.msmq://{0}/private/nc_queue" />
    </dataPortalProxy>
    <dataPortalProxy isEnabled="true" name="Peer Agent" endpointKind="Agent" implementation="Shunra.Common.Csla.WcfDynamicProxy, Shunra.Common">
      <add key="AddressTemplate" value="https://{0}:7000/NCAgent/WcfPortal.svc" />
    </dataPortalProxy>
  </dataPortalProxies>

What I want is some kind of wrap long lines for attributes, so that any attributes exceeding certain line width are indented on the following line. In short pretty printing.


You should never use new XmlTextWriter() is has been deprecated since .NET 2.0.

Use XmlWriter.Create() instead:

XmlWriterSettings settings = 
    new XmlWriterSettings {Indent = true, NewLineOnAttributes = true};
using (var writer = XmlWriter.Create("path", settings))
{

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜