【问题标题】:Set Root Namespace Prefix in an XDocument [duplicate]在 XDocument 中设置根命名空间前缀 [重复]
【发布时间】:2013-02-20 18:05:03
【问题描述】:

我目前有:

XNamespace xmlns = "XSDName";<br>
XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";<br>
XNamespace schemaloc = @"XSDName XSDName.xsd";
XDocument xdoc = new XDocument(
    new XElement("BaseReport",
    new XAttribute(xsi + "schemaLocation", schemaloc),
    new XAttribute(XNamespace.Xmlns+"ns1", xmlns),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi));

这给了我:

BaseReport xsi:schemaLocation="XSDName XSDName .xsd" xmlns:ns1="XSDName" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

我怎样才能让BaseReport 读取ns1:BaseReport

【问题讨论】:

  • 您能否将变量xsischemalocxmlns 的赋值添加到您的代码示例中?
  • 在做了额外的研究之后,我不相信你可以在根元素中使用命名空间。命名空间被定义为根元素的属性,并且对于根本身是未定义的。你可以阅读更多here
  • 但是,当我使用 XMLSpy 之类的东西从 XSD 生成示例 xml 时,它使用“ns1:BaseReport”作为标题标签...
  • 而且它没有在更高级别声明ns1 命名空间?它在哪里声明这个命名空间?
  • XMLSpy 生成器生成一个带有 xml 标头的 xml,与我希望对代码执行的操作相同,我只是不知道如何在代码中获取“ns1:BaseReport”部分,所以它可以正确验证。

标签: c# xml xsd linq-to-xml xelement


【解决方案1】:

以下代码将为您提供所需的输出。关键是在名称前添加定义的命名空间,并让 .NET 找出正确的前缀。

XNamespace xmlns = "XSDName";
XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";
XNamespace schemaloc = @"XSDName XSDName.xsd";
XDocument xdoc = new XDocument(
    new XElement(xmlns + "BaseReport",
    new XAttribute(xsi + "schemaLocation", schemaloc),
    new XAttribute(XNamespace.Xmlns + "ns1", xmlns),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi)));

【讨论】:

  • 啊,是的,我从您发送的上一个链接中得到了这个 +/- 一些摆弄。 [页面没有刷新,笨蛋。] 非常感谢!
  • @user2073374 没问题,很高兴能帮上忙。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
相关资源
最近更新 更多