【问题标题】:Reading oddly-formatted XML file C#读取格式奇特的 XML 文件 C#
【发布时间】:2012-07-25 23:58:28
【问题描述】:

我需要一些帮助来阅读格式奇怪的 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;

【问题讨论】:

  • &lt;ApplicationMonitoring&gt; 似乎没有结束标签
  • 如果这是整个文档,那是非法的 XML,因为 ApplicationMonitoring 根元素永远不会关闭,这可能解释了您的问题。这就是您要解析的全部内容吗?
  • 它不是有效的 XML,因为没有关闭 &lt;ApplicationMonitoring&gt; 标记。
  • 不,这只是我的一个糟糕的副本。它有一个结束标签。
  • @Skulmuk:那么你应该确保它存在于问题中......

标签: c# xml


【解决方案1】:

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

尝试改用:

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

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

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

而且我相信您现在可以看到为什么会出现解析异常。 :) 我已经用您的 xml 文档和修改后的负载对此进行了测试,它工作正常(除了 Only Bolivian Here 指出的问题,即您的内部 Text 不会返回任何内容。

为了完整性,您可能想要:

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 中提取数据的确切方式可能取决于您使用它做什么。例如,您可能希望通过执行此xml.SelectNodes("//Application") 来获取要使用 foreach 枚举的应用程序节点列表。

如果您在提取内容时遇到问题,但这可能是另一个问题的范围,因为这只是关于如何加载 XML 文档。

【讨论】:

  • 效果很好 ;) 请问您如何建议阅读函数名称,看看每个函数名称有何不同?我怀疑 xml.DocumentElement[""] 会起作用....
  • 我在选择中添加了更多内容(包括使属性选择明确,因为如果属性更改顺序或其他内容,使用整数有点脆弱)。不要忘记您可以投票选出对您有帮助的答案,我还建议您在另一个问题中询问有关通过 XPath 提取数据的任何问题。
【解决方案2】:
xml.DocumentElement["proxyAgent"].InnerText;

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

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

【讨论】:

  • 你的意思是这样的?字符串端口 = xml.DocumentElement["proxyAgent"].Attributes[0].ToString();
【解决方案3】:

试试这个:

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

或者使用 Linq to XML:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2010-11-14
    相关资源
    最近更新 更多