c# - 如何创建具有特定命名空间的 XElement?

标签 c# .net xml linq-to-xml

我在 LinqToXml 中创建新元素时遇到问题。 这是我的代码:

XNamespace xNam = "name"; 
XNamespace _schemaInstanceNamespace = @"http://www.w3.org/2001/XMLSchema-instance";

XElement orderElement = new XElement(xNam + "Example",
                  new XAttribute(XNamespace.Xmlns + "xsi", _schemaInstanceNamespace));

我想得到这个:

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

但是在 XML 中我总是得到这样的信息:

<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="name">

我做错了什么?

最佳答案

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">命名空间不是格式正确的前缀 name未声明。所以用 XML API 构建它是不可能的。您可以做的是构造以下 namespace 格式正确的 XML

<name:Example xmlns:name="http://example.com/name" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />

代码

//<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="http://example.com/name"></name:Example>

XNamespace name = "http://example.com/name";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

XElement example = new XElement(name + "Example",
new XAttribute(XNamespace.Xmlns + "name", name),
new XAttribute(XNamespace.Xmlns + "xsi", xsi));

Console.WriteLine(example);

关于c# - 如何创建具有特定命名空间的 XElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12050067/

相关文章:

c# - 如何在 asp.net 中获取链接的 http 类型(http 或 https)的完整域?

javascript - angularjs - 语法错误 : Unexpected token when request return from server

c# - NHibernate LINQ 计算查询中的组数

c# - Dataset.WriteXml() 命名空间和前缀

android - 在进行第二项 Activity 之前验证电子邮件地址

c# - C# 中的 XML 序列化

c# - 如何用 winapi 获取监视器的友好名称?

.net - 在 vb.net 中创建并写入文本文件

.net - 是否可以用 "weak"引用替换对强名称程序集的引用?

c++ - 通用的 XML QDomElement 比较 - C++/Qt