Rai*_*con 31 c# xml xml-namespaces
我正在尝试使用C#生成以下xml元素.
<Foo xmlns="http://schemas.foo.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://schemas.foo.com
http://schemas.foo.com/Current/xsd/Foo.xsd">
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我得到了异常:前缀"无法从"重新定义到相同的start元素标记内.这是我的c#代码:
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XElement foo = new XElement("Foo", new XAttribute("xmlns", "http://schemas.foo.com"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "schemaLocation", "http://schemas.foo.com http://schemas.foo.com/Current/xsd/Foo.xsd"));
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?我正在尝试将生成的xml作为SOAP消息的主体发送,我需要它以接收器的这种格式.
编辑:我在另一个问题上找到了答案.控制XML名称空间的顺序
Jos*_* M. 28
您需要指明该元素Foo
是命名空间的一部分http://schemas.foo.com
.试试这个:
XNamespace xNamespace = "http://schemas.foo.com";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XElement foo = new XElement(
xNamespace + "Foo",
new XAttribute("xmlns", "http://schemas.foo.com"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "schemaLocation", "http://schemas.foo.com http://schemas.foo.com/Current/xsd/Foo.xsd")
);
Run Code Online (Sandbox Code Playgroud)
创建 XDocument 时出现此错误。经过大量的谷歌搜索,我找到了这篇文章:
文档中恰好有一个解释,我很幸运地发现了。
关键是您的代码应该让 XDocument 处理 xmlns 属性。创建 XElement 时,您的第一直觉是像其他所有属性一样设置命名空间属性,方法是添加属性“xmlns”并将其设置为值。
相反,您应该创建一个 XNamespace 变量,并在定义 XElement 时使用该 XNamespace 变量。这将有效地为您的元素添加一个 XAttribute。
当您自己添加 xmlns 属性时,您是在告诉 XElement 创建例程在没有命名空间的情况下创建 XElement,然后使用保留的 xmlns 属性更改命名空间。你在自相矛盾。错误说“你不能将命名空间设置为空,然后再将命名空间设置为同一标签中的其他内容,你这个笨蛋。”
下面的函数说明了这一点......
private static void Test_Namespace_Error(bool doAnError)
{
XDocument xDoc = new XDocument();
string ns = "http://mynamespace.com";
XElement xEl = null;
if (doAnError)
{
// WRONG: This creates an element with no namespace and then changes the namespace
xEl = new XElement("tagName", new XAttribute("xmlns", ns));
}
else
{
// RIGHT: This creates an element in a namespace, and implicitly adds an xmlns tag
XNamespace xNs = ns;
xEl = new XElement(xNs + "tagName");
}
xDoc.Add(xEl);
Console.WriteLine(xDoc.ToString());
}
Run Code Online (Sandbox Code Playgroud)