【问题标题】:XmlReader can't parse XML with <qn:xxxxx> format?XmlReader 无法解析 <qn:xxxxx> 格式的 XML?
【发布时间】:2013-07-15 14:48:55
【问题描述】:

我正在尝试解析以下 xml 字符串:

<qn:QueryNotification xmlns:qn="http://schemas.microsoft.com/SQL/Notifications/QueryNotification" id="307" type="change" source="data" info="insert" database_id="6" sid="0x010500000000000515000000AEA63BDE2DE94B9FF38541A8CD1A0000">
  <qn:Message>Custom</qn:Message>
</qn:QueryNotification>

我正在通过以下方式使用 XmlReader:

using (XmlReader xmlReader = XmlReader.Create(new StringReader(z)))
{
     xmlReader.Read();
}

执行 Read() 时,出现以下异常:

XmlException:根级别的数据无效。第 1 行,位置 40。

我不认为它喜欢每个标签之前的 qn:。如何设置 XmlReader 来解析此文档?

【问题讨论】:

  • z 的值究竟是什么?它说错误位于“位置 40”,但是您在问题中发布的 xml 中的 40 个字符位于名称空间 URI 的中间。如果我将您的代码与var z="&lt;qn:QueryNotification xmlns:qn=\"http://schemas.microsoft.com/SQL/... 一起使用,则不会出错。这告诉我您发布的内容不是z 的实际值。
  • 嗯...我正在从这样的 Unicode 字符串中解析 z:string z = Encoding.Unicode.GetString(binaryString);不知是否有隐藏无效字符...
  • 什么是二进制字符串?你能打印出 z 的值吗?
  • z 的原始复制/粘贴值是 schemas.microsoft.com/SQL/Notifications/QueryNotification" id="464" type="change" source="data" info="insert" database_id="6" sid="0x010500000000000515000000AEA63BDE2DE94B9FF38541A8CD1A0000">自定义
  • 将其粘贴到记事本中会在某些位置显示小于应有的文本。我将尝试在解析之前将其转换为 UTF-8 字符串。

标签: c# xmlreader


【解决方案1】:

您的 xml 已声明命名空间。解析节点时应该考虑它。我建议你使用 Linq to XML:

XNamespace qn = "http://schemas.microsoft.com/SQL/Notifications/QueryNotification";
XElement notification = XElement.Parse(z);
var message = (string)notification.Element(qn + "Message"); // Custom

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    相关资源
    最近更新 更多