我正在尝试使用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">
我遇到的问题是我得到了例外:
前缀“无法从”重新定义到同一个起始元素标记内。
这是我的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"));
我怎样才能解决这个问题?我正在尝试将生成的xml作为SOAP消息的主体发送,我需要它以接收器的这种格式。
编辑:我在另一个问题上找到了答案。 Controlling the order of XML namepaces
您需要指明元素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")
);