读奇怪格式的XML文件C#

时间:2012-07-25 15:33:04

标签: c# xml

我需要一些帮助来阅读奇怪格式的XML文件。由于节点和属性的结构方式,我不断遇到XMLException错误(至少,输出窗口告诉我的是什么;我的断点拒绝触发,以便我可以检查它)。无论如何,这里是XML。以前有人经历过这样的事吗?

<ApplicationMonitoring>
<MonitoredApps>
        <Application>
            <function1 listenPort="5000"/>
        </Application>
        <Application>
            <function2 listenPort="6000"/>
        </Application>
</MonitoredApps>
<MIBs>
    <site1 location="test.mib"/>
</MIBs> 
<Community value="public"/>
<proxyAgent listenPort="161" timeOut="2"/>
</ApplicationMonitoring>

干杯

编辑:当前版本的解析代码(文件路径缩短 - 我实际上并没有使用这个):

XmlDocument xml = new XmlDocument();
xml.LoadXml(@"..\..\..\ApplicationMonitoring.xml");

string port = xml.DocumentElement["proxyAgent"].InnerText;

3 个答案:

答案 0 :(得分:1)

加载XML时遇到的问题是xml.LoadXml要求您将xml文档作为字符串传递,而不是文件引用。

请尝试使用:

xml.Load(@"..\..\..\ApplicationMonitoring.xml");

基本上在您的原始代码中,您告诉它您的xml文档是

..\..\..\ApplicationMonitoring.xml

我相信你现在可以看到为什么会有一个解析异常。 :)我已经用你的xml文档和修改后的加载测试了这个并且它工作正常(除了这里只有Bolivian指出的问题,你的内部文本不会返回任何东西。

为了完整,你可能想要:

XmlDocument xml = new XmlDocument();
xml.Load(@"..\..\..\ApplicationMonitoring.xml");
string port = xml.DocumentElement["proxyAgent"].Attributes["listenPort"].Value;
//And to get stuff more specifically in the tree something like this
string function1 = xml.SelectSingleNode("//function1").Attributes["listenPort"].Value;

注意在属性上使用Value属性而不是ToString方法,它不会达到你期望的效果。

从xml中提取数据的确切方式可能取决于您使用它做了什么。例如,您可能希望获取一个Application节点列表,通过执行此操作xml.SelectNodes("//Application")来枚举foreach。

如果你遇到问题,那可能是另一个问题的范围,因为这只是关于如何加载XML文档。

答案 1 :(得分:0)

xml.DocumentElement["proxyAgent"].InnerText;

proxyAgent元素是自动关闭的。 InnerText将返回XML元素内部的字符串,在这种情况下,没有内部元素。

您需要访问元素的属性,而不是InnerText。

答案 2 :(得分:0)

试试这个:

string port = xml.GetElementsByTagName("ProxyAgent")[0].Attributes["listenPort"].ToString();

或者使用Linq to XML:

http://msdn.microsoft.com/en-us/library/bb387098.aspx

而且......你的XML没有格式错误......

相关问题