包含名称空间的XML元素的XDocument或XElement解析 [英] XDocument or XElement parsing of XML element containing namespaces

查看:76
本文介绍了包含名称空间的XML元素的XDocument或XElement解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取从log4net UdpAppender中捕获的以下字符串.

I am try to read the following string, captured from a log4net UdpAppender.

<log4net:event logger="TestingTransmitter.Program" 
               timestamp="2009-08-02T17:50:18.928+01:00" 
               level="ERROR" 
               thread="9" 
               domain="TestingTransmitter.vshost.exe" 
               username="domain\user">
    <log4net:message>Log entry 103</log4net:message>
    <log4net:properties>
        <log4net:data name="log4net:HostName" value="machine" />
    </log4net:properties>
</log4net:event>

当尝试XElement.Parse或XDocument.Parse内容时,它引发异常:

When trying to XElement.Parse or XDocument.Parse the content, it throws an exception:

'log4net'是未声明的名称空间. 第1行,位置2.

'log4net' is an undeclared namespace. Line 1, position 2.

我知道我可以搜索并替换原始字符串中的"log4net:"并将其删除,从而使我能够成功解析XML,但是还有更好的方法吗?这是捕获的完整数据(经过重新格式化以允许读取),没有创建或删除xml命名空间声明..

I know I can search and replace "log4net:" in the original string and remove it, allowing me to parse the XML successfully, but is there a better way? This is the complete data captured (reformatted to allow reading), there are no xml namespace declarations made or removed..

推荐答案

首先,创建XmlNamespaceManager类的实例,然后向其中添加名称空间,例如

First, create an instance of XmlNamespaceManager class, and add your namespaces to that, e.g.

    XmlNamespaceManager mngr = new XmlNamespaceManager( new NameTable() );
    mngr.AddNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );
    mngr.AddNamespace( "xsd", "http://www.w3.org/2001/XMLSchema" );

要使用这些名称空间映射来解析XML字符串,请调用以下函数,将XmlNamespaceManager的实例与您添加到其中的名称空间一起传递:

To parse an XML string using those namespace mappings, call the following function, passing the instance of XmlNamespaceManager with the namespaces you've added to it:

/// <summary>Same as XElement.Parse(), but supports XML namespaces.</summary>
/// <param name="strXml">A String that contains XML.</param>
/// <param name="mngr">The XmlNamespaceManager to use for looking up namespace information.</param>
/// <returns>An XElement populated from the string that contains XML.</returns>
public static XElement ParseElement( string strXml, XmlNamespaceManager mngr )
{
    XmlParserContext parserContext = new XmlParserContext( null, mngr, null, XmlSpace.None );
    XmlTextReader txtReader = new XmlTextReader( strXml, XmlNodeType.Element, parserContext );
    return XElement.Load( txtReader );
}

这篇关于包含名称空间的XML元素的XDocument或XElement解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆