2015-06-19 116 views
0

我试图让下面的XML(为第三方,所以需要准确),并具有对内部元件一些麻烦与的xmlns:使用名称空间创建XElement?

<headerResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <sessionID xmlns="http://www.example.com/portal-api">4654654564</sessionID> 
    <uniqueTranID xmlns="http://www.example.com/portal-api">gh0000000</uniqueTranID> 
    <statusCode xmlns="http://www.example.com/portal-api">1</statusCode> 
    <statusCodeDescription xmlns="http://www.example.com/portal-api">jhkjhkjhkjhkjkjhkjkkjhkhk</statusCodeDescription> 
    <message xmlns="http://www.example.com/portal-api">testMessage</message> 
</headerResponse> 

从其他的例子,我已经拿到了以下:

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

XElement example = new XElement("headerResponse", 
    new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
    new XAttribute(XNamespace.Xmlns + "xsd", xsd), 
    new XElement("sessionID", "some session id", new XAttribute("xmlns", api)) 
); 

没有会话ID,它高兴地创建主headerResponse与XSI和XSD,但是当我加入的SessionID中,并尝试与example.toString()张贴在即时窗口中的内容,我得到以下错误:

The prefix '' cannot be redefined from '' to 'http://www.example.com/portal-api' within the same start element tag. 

回答

3

您需要定义元素名称sessionID及其完全限定名称(即,包括它的名字空间)。默认命名空间声明的插入会自动LINQ处理,以XML:

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

XElement example = new XElement("headerResponse", 
    new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
    new XAttribute(XNamespace.Xmlns + "xsd", xsd), 
    new XElement(api + "sessionID", "some session id") 
); 

您可以将其添加为你已经完成了控制的声明。例如,你可以用一个前缀添加一个声明api为根,以简化结果:

XElement example = new XElement("headerResponse", 
    new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
    new XAttribute(XNamespace.Xmlns + "xsd", xsd), 
    new XAttribute(XNamespace.Xmlns + "api", api), 
    new XElement(api + "sessionID", "some session id") 
); 

注意的是,虽然XML看起来你需要XML不同,但在语义上是没有差别。

+0

那(第一个例子)是PERFECT – Sean