由于各种原因,我想从以下scala elem对象中仅删除作用域的某些部分。我知道xmlns被定义了两次,这是我的程序失败的部分原因,但这是我必须使用的服务来处理。
val dataXML = <DataSet xmlns="" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<Table BillCycleCode="20131218" Amount="135.6200" BillEndDate="2014-01-17T00:00:00-06:00" BillStartDate="2013-12-18T00:00:00-06:00" msdata:rowOrder="0" diffgr:id="Table1"/>
<Table BillCycleCode="20140118" Amount="126.5500" BillEndDate="2014-02-17T00:00:00-06:00" BillStartDate="2014-01-18T00:00:00-06:00" msdata:rowOrder="1" diffgr:id="Table2"/>
<Table BillCycleCode="20140218" Amount="126.5500" BillEndDate="2014-03-17T00:00:00-05:00" BillStartDate="2014-02-18T00:00:00-06:00" msdata:rowOrder="2" diffgr:id="Table3"/>
</DataSet>
dataXML.scope显示以下内容:
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns=""
基本上我希望能够进行某种过滤,以便if(specialNamespace!= xmlns:diffgr =&#34; urn:schemas-microsoft-com:xml-diffgram-v1&#34; OR specificNamespace!= xmlns:msdata =&#34; urn:schemas-microsoft-com:xml-msdata&#34;)删除specialNamespace。
我的最终结果应该是这样的:
<DataSet xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<Table BillCycleCode="20131218" Amount="135.6200" BillEndDate="2014-01-17T00:00:00-06:00" BillStartDate="2013-12-18T00:00:00-06:00" msdata:rowOrder="0" diffgr:id="Table1"/>
<Table BillCycleCode="20140118" Amount="126.5500" BillEndDate="2014-02-17T00:00:00-06:00" BillStartDate="2014-01-18T00:00:00-06:00" msdata:rowOrder="1" diffgr:id="Table2"/>
<Table BillCycleCode="20140218" Amount="126.5500" BillEndDate="2014-03-17T00:00:00-05:00" BillStartDate="2014-02-18T00:00:00-06:00" msdata:rowOrder="2" diffgr:id="Table3"/>
</DataSet>
我在scala中使用xml相当新,所以任何帮助都将非常感谢!谢谢大家!
答案 0 :(得分:0)
你需要的代码应该看起来像这样(我没有测试它,但只写了类似的东西):
def yourFilterFunction(prefix : String) : Boolean = ....
def scopeFilter(scope : NamespaceBinding) : NamespaceBinding =
if (scope == TopScope) TopScope else
if (yourFilterFunction(scope.prefix))
new NamespaceBinding(scope.prefix, scope.uri, scopeFilter(scope.parent))
else
scopeFilter(scope.parent)
def removeScopes(node : Node) : Node = node match {
case Elem(prefix, label, attr, scope, children @ _*) =>
Elem(prefix, label, attr, scopeFilter(scope), children.map(removeScopes(_)):_*)
case _ => node
}
您需要实现针对每个未使用的前缀返回false的过滤器函数。然后,您可以在Element节点上调用removeScopes。
祝你好运