c# - 在 XDocument 中设置根命名空间前缀

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

我目前有:

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

最佳答案

下面的代码将为您提供您想要的输出。关键是在名称之前添加定义的命名空间,并让 .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)));

关于c# - 在 XDocument 中设置根命名空间前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14986859/

相关文章:

java - 是否可以从 DTD 自动生成 Java 类?

java - 使用 XSD、目录解析器和用于 XSLT 的 JAXP DOM 验证 XML

c# - 如何从 BsonDocument 中正确选择元素的值

javascript - 努力保持 ViewModel 数据在下拉回发中

xml - 索引 JSON 或 XML

XSD 文件的 XML::Compile::Schema 错误

java - XSD 验证 : This parser does not support specification "null" version "null"

c# - 在SortFieldDescriptor中使用.Suffix

c# - 在分配对象之前引用对象的最佳方法?

java - 工具 :replace=android:value to &lt;meta-data> element at AndroidManisfest. xml:25:5-17:34 覆盖