我在 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/