C#XMLElement.OuterXML在一行而不是格式

时间:2011-10-12 17:52:42

标签: c# .net xml tostring

我正在尝试使用log4net从WCF服务记录一些XML响应。

我希望XML文件的输出到日志中的格式正确。该请求以XMLElement形式出现。

示例:

请求如下:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationEvent xmlns="http://courts.wa.gov/INH_TV/ApplicationEvent.xsd">
  <Severity xmlns="">Information</Severity>
  <Application xmlns="">Application1</Application>
  <Category xmlns="">Timings</Category>
  <EventID xmlns="">1000</EventID>
  <DateTime xmlns="">2012-09-02T12:05:15.234Z</DateTime>
  <MachineName xmlns="">Server1</MachineName>
  <MessageID xmlns="">10000000-0000-0000-0000-000000000000</MessageID>
  <Program xmlns="">Progam1</Program>
  <Action xmlns="">Entry</Action>
  <UserID xmlns="">User1</UserID>
</ApplicationEvent>

然后,如果我将此值输出到log4net。

logger.Info(request.OuterXml);

我将整个文档记录在一行中,如下所示:

<ApplicationEvent xmlns="http://courts.wa.gov/INH_TV/ApplicationEvent.xsd"><Severity xmlns="">Information</Severity><Application xmlns="">Application1</Application><Category xmlns="">Timings</Category><EventID xmlns="">1000</EventID><DateTime xmlns="">2012-09-02T12:05:15.234Z</DateTime><MachineName xmlns="">Server1</MachineName><MessageID xmlns="">10000000-0000-0000-0000-000000000000</MessageID><Program xmlns="">Progam1</Program><Action xmlns="">Entry</Action><UserID xmlns="">User1</UserID></ApplicationEvent>

我希望它在log.txt文件中显示格式正确,因为它进入。到目前为止,我发现这样做的唯一方法是将其转换为XElement,如下所示:

XmlDocument logXML = new XmlDocument();
logXML.AppendChild(logXML.ImportNode(request, true));
XElement logMe = XElement.Parse(logXML.InnerXml);
logger.Info(logMe.ToString());

这对我来说似乎不是一个好的编程。我一直在搜索文档,我找不到一种内置的方法来正确输出它而不转换它。

是否有一种明显的,更好的方式让我失踪?

edit1:删除了ToString(),因为OuterXML是一个String值。

edit2:我回答了我自己的问题:

所以我做了一些研究,我想我错过了文档中的一段代码。

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.outerxml.aspx

我明白了:

using (MemoryStream ms = new MemoryStream())
        {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Indent = true;
            using (XmlWriter xmlWriter = XmlWriter.Create(ms, xws))
            {
                request.WriteTo(xmlWriter);
            }
            ms.Position = 0; StreamReader sr = new StreamReader(ms);
            string s = sr.ReadToEnd(); // s will contain indented xml
            logger.Info(s);
        }

尽管比较冗长,但这比我现在的方法更有效率。

1 个答案:

答案 0 :(得分:12)

XElement解析是最干净的方法。您可以使用以下内容保存一行或两行

logger.Info(XElement.Parse(request.OuterXml).ToString());