【问题标题】:how do you check if a namespace exists at all?你如何检查一个命名空间是否存在?
【发布时间】:2018-10-22 20:24:08
【问题描述】:

我们可以用下面的方法列出所有的命名空间:

public static class NamespaceGetter
{
    public static IDictionary<string, string> Get(string xml)
    {
        XPathDocument x = new XPathDocument(new StringReader(xml));
        XPathNavigator foo = x.CreateNavigator();
        foo.MoveToFollowing(XPathNodeType.Element);
        return foo.GetNamespacesInScope(XmlNamespaceScope.All);
    }
}

但是,如果string xml 参数没有定义命名空间,那么这个方法会抛出异常。

例如下面的payload会导致异常

<MyXml>
  <Cars>4</Cars>
  <Burgers>3</Burgers>
</MyXml>

如何检查字符串是否定义了 XML 命名空间?

上面的输出将返回:

这真的没有意义。

【问题讨论】:

  • The prefix xml is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace. It MAY, but need not, be declared, and MUST NOT be bound to any other namespace name。您可以只排除w3.org/XML/1998/namespace 或前缀 xml - 实际上它不太可能被明确定义,如果是,那又如何?
  • 当您将字符串读入您的域时,希望它是 XML,如果不是,则采取措施形成有效的 XML,当外部库在没有您的情况下向您的对象添加名称空间时,这是一个障碍知道,就是这样。
  • 当我尝试使用示例代码时没有出现异常。 XmlNamespaceScope 有一个不包括 XML 的值,它仍然不返回异常,只是一个空的 Dictionary。你认为代码抛出了什么异常?

标签: c# xml xsd


【解决方案1】:

您的代码看起来不错。

但是你的 XML 字符串无效:抛出的异常是:

The 'MyXml' start tag on line 2 position 4 does not match the end tag of 'MyXML'

XML 区分大小写。

【讨论】:

  • 我添加了更多信息
猜你喜欢
  • 1970-01-01
  • 2013-09-10
  • 2012-12-22
  • 2018-04-04
  • 2015-08-17
  • 1970-01-01
  • 2011-02-06
  • 2010-09-19
  • 2014-04-19
相关资源
最近更新 更多