java是否可以在父标记和子标记中编写XMLSchemainstance?
我想创建下面的XML,它具有xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“在“ServiceAddRQ”和“Service”标签中。那么有可能创建这样的XML吗
必需的XML:
<ServiceAddRQ echoToken="DummyEchoToken" version="2013/12"
xmlns="http://www.test.com/schemas/2005/06/messages"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.test.com/schemas/2005/06/messages ServiceAddRQ.xsd">
<Service xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ServiceHotel" availToken="1jMqWGjqrx25Bp60gV2Qggb3">
</Service>
</ServiceAddRQ>
Java生成的XML:在Java生成的代码中,我得到了“服务”标签的空白XMLN
<ServiceAddRQ xmlns="http://www.test.com/schemas/2005/06/messages"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" echoToken="6BB6B47EEEF4290515103925"
version="2013/12"
xsi:schemaLocation="http://www.test.com/schemas/2005/06/messages HotelValuedAvailRQ.xsd">
<Service xmlns="" xsi:type="ServiceHotel" availToken="1/YncBXZJXY17Z/ygNiO7gcg">
</Service>
</ServiceAddRQ>
同样的Java代码:
static private Namespace NSSERVICE = Namespace.getNamespace("http://www.test.com/schemas/2005/06/messages");
static private Namespace NSSCHEMA = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
String sXMLOut = "";
Element barceloDS_requests= new Element("ServiceAddRQ",NSSERVICE);
barceloDS_requests.setAttribute("echoToken",searchParams.getSessionID().substring(0, 12)+GenTools.getSystemDateWithTime3());
barceloDS_requests.setAttribute("version","2013/12");
barceloDS_requests.addNamespaceDeclaration(NSSCHEMA);
barceloDS_requests.setAttribute("schemaLocation", "http://www.test.com/schemas/2005/06/messages HotelValuedAvailRQ.xsd", NSSCHEMA);
Namespace xsi = Namespace.getNamespace(GenTools.returnEmptyForNull(sXMLNS_XSI), "http://www.w3.org/2001/XMLSchema-instance");
Element eleService=new Element("Service");
eleService.setAttribute("type", "ServiceHotel", xsi);
eleService.setAttribute("availToken",contractInfo[1]);
barceloDS_requests.addContent(eleService);
sXMLOut = new GetXMLOutputter().getXMLOutputter(barceloDS_requests,true);
# 1 楼答案
序列化程序添加
xmlns=""
是正确的,因为您创建了一个带有默认名称空间声明的顶级元素,但随后添加了一个不在名称空间中的子元素。要获得所需的输出,需要创建Service
元素,其http://www.test.com/schemas/2005/06/messages
名称空间与根ServiceAddRQ
名称空间相同。试着像这样做:这将创建以下各项的正确输出:
Service
元素不需要自己的xmlns:xsi
声明,因为这是从父元素继承的,但是,如果您特别想添加一个冗余的名称空间声明,那么可以使用eleService.addNamespaceDeclaration(NSSCHEMA)
来但是没有保证,因为序列化程序在不改变结果语义的情况下总是可以自由地省略冗余的名称空间声明