如何为XML的每个元素添加前缀。
所以一般来说,从这样的XML来看:
<CLASSXml>
<CalculationIndex>
<RunDesc>NormalCalc</RunDesc>
</CalculationIndex>
<GlobalData>
<CalcIdent>
<CalcUId>CLASS:20160105:09411486:000007773000:203:CS:CZK:349074</CalcUId>
<CalcNo>2454307119</CalcNo>
<CustomNo>349074</CustomNo>
<CalcVer>2300</CalcVer>
<XMLVer>23.00.01</XMLVer>
<Detail>
<Current>1123</Current>
<Last>1152</Last>
</Detail>
<ClassBuild>23.00.04.03</ClassBuild>
<SAXIFVersion>6.2</SAXIFVersion>
<SystemDat>2016-01-05</SystemDat>
<TimeStamp>09:41:14.86</TimeStamp>
<ProdMasterVer>0</ProdMasterVer>
</CalcIdent>
</GlobalData>
</CLASSXml>
制作这样的东西:
<ns2:CLASSXml>
<ns2:CalculationIndex>
<ns2:RunDesc>NormalCalc</ns2:RunDesc>
</ns2:CalculationIndex>
<ns2:GlobalData>
<ns2:CalcIdent>
<ns2:CalcUId>CLASS:20160105:09411486:000007773000:203:CS:CZK:349074</ns2:CalcUId>
<ns2:CalcNo>2454307119</ns2:CalcNo>
<ns2:CustomNo>349074</ns2:CustomNo>
<ns2:CalcVer>2300</ns2:CalcVer>
<ns2:XMLVer>23.00.01</ns2:XMLVer>
<ns2:Detail>
<ns2:Current>1123</ns2:Current>
<ns2:Last>1152</ns2:Last>
</ns2:detail>
<ns2:ClassBuild>23.00.04.03</ns2:ClassBuild>
<ns2:SAXIFVersion>6.2</ns2:SAXIFVersion>
<ns2:SystemDat>2016-01-05</ns2:SystemDat>
<ns2:TimeStamp>09:41:14.86</ns2:TimeStamp>
<ns2:ProdMasterVer>0</ns2:ProdMasterVer>
</ns2:CalcIdent>
</ns2:GlobalData>
</ns2:CLASSXml>
我知道用str_replace可以做这样的事情(如下例),但如果XML变成500行长或类似的东西,它只是大量混乱的代码,是没有用的。
有什么想法吗?我怎么能这么简单?
public function addNameSpace($xml) {
$xml = str_replace('<CLASSXml>', '<ns2:CLASSXml>', $xml);
$xml = str_replace('</CLASSXml>', '</ns2:CLASSXml>', $xml);
$xml = str_replace('<CalculationIndex>', '<ns2:CalculationIndex>', $xml);
$xml = str_replace('</CalculationIndex>', '</ns2:CalculationIndex>', $xml);
// What to do?
}
在PHP中使用regex,将非常容易
$xmlString = preg_replace( '/(?<='<)([^'/].*?)(?='>)/', 'ns2:$1', $xmlString); // for <test>
$xmlString = preg_replace( '/(?<='<'/)(.*?)(?='>)/', 'ns2:$1', $xmlString); // for </test>
其中$xmlString是您的xml内容。
您的功能
public function addNameSpace($xml)
{
$xml = preg_replace( '/(?<='<)([^'/].*?)(?='>)/', 'ns2:$1', $xml );
$xml = preg_replace( '/(?<='<'/)(.*?)(?='>)/', 'ns2:$1', $xml );
.
.
}
或建议:用于不同的命名空间
public function addNameSpace($xml, $namespace)
{
$xml = preg_replace( '/(?<='<)([^'/].*?)(?='>)/', $namespace.'$1', $xml );
$xml = preg_replace( '/(?<='<'/)(.*?)(?='>)/', $namespace.'$1', $xml );
.
.
}
现在您正在使用哪种技术。。spring中有一种方法,可以为每个元素添加前缀。。
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
@Override
public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
return "ns1";
}
});'
或者还有另一种方法可以实现
@XmlSchema(
namespace = "http://www.example.com/a",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(prefix="ns1", namespaceURI="http://www.example.com/a")
}
)
package authenticator.beans.login;
import javax.xml.bind.annotation.*;