// start with a sample xml 'document'
val xml = <root attr="willIStayOrWillIGoAway"><container/></root>
// create a namespace binding using TopScope as the "parent" argument
val ns = new NamespaceBinding("ns", "http://example.com/ns", TopScope)
// create a second namespace binding, and pass "ns" as the new parent argument
val xsi = new NamespaceBinding("xsi", "http://www.w3.org/2001/XMLSchema-instance", ns)
알 수 있습니다.
// the schemaLocation needs to be a PrefixedAttribute
val schemaLoc = new PrefixedAttribute("xsi", "schemaLocation", "http://example.com/ns http://example.com/xml/xsd/xml-schema-articles-v1.0.xsd", Null)
xmlns:ns
및 xmlns:xsi
속성은 실제로 NamespaceBindings있다 - 나는 그들이 다르게 처리하는 이유를 모르겠어요. 그러나 xsi:schemaLocation
은 실제로 범위가 지정된 속성이므로 PrefixedAttribute을 사용합니다.
// in order to limit the insertion to the root node, you'll need it's label
val rootNodeLabel = "root"
// make a new RewriteRule object
val setSchemaAndNamespaceRule = new setNamespaceAndSchema(rootNodeLabel, xsi, schemaLoc)
// apply the rule with a new transformer
val newxml = new RuleTransformer(setSchemaAndNamespaceRule).transform(xml).head
변압기를 적용하면이 결과가 반환됩니다.
newxml: scala.xml.Node =
<root attr="willIStayOrWillIGoAway"
xmlns:ns="http://example.com/ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://example.com/ns http://example.com/xml/xsd/xml-schema-articles-v1.0.xsd">>
<container/>
</root>
그리고 이것은 다시 쓰기 규칙을 반환하는 클래스입니다.
// new class that extends RewriteRule
class setNamespaceAndSchema(rootLabel: String, ns: NamespaceBinding, attrs: MetaData) extends RewriteRule {
// create a RewriteRule that sets this as the only namespace
override def transform(n: Node): Seq[Node] = n match {
// ultimately, it's just a matter of setting the scope & attributes
// on a new copy of the xml node
case e: Elem if(e.label == rootLabel) =>
e.copy(scope = ns, attributes = attrs.append(e.attributes))
case n => n
}
}
원본 속성이 유지됩니다. 우리의 확장 된 RewriteRule 클래스가 schemaLocation 속성을 어떻게 직접 추가하지 않고 추가하는지 확인하십시오.
XML을 어떻게 생성합니까? – mfirry
실제로 파일에서 오래된 XML을 읽고 scala.xml.transform RewriteRules를 사용하여 수정했습니다. – doub1ejack