2016-09-08 1 views
0

나는 XML 파일을 생성하고 일부는 루트 요소에 다음을 삽입합니다의 RewriteRules 변환 만들려고 해요 :Scala RewriteRules 네임 스페이스 및 schemaLocation을 설정 하시겠습니까?

<content 
    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"> 

그것은 xmls:ns 네임 스페이스를 설정하는 것은 NamespaceBinding을 만들고 적용의 문제가 있음을 from this gist 모습을 그것은 엘름의 범위입니다. 그러나 아직 RewriteRule을 성공적으로 만들지 못했지만 아직 스키마 인스턴스 (xmlns:xsi)와 schemaLocation을 추가하는 방법을 찾고 있습니다. 우리는이 NamespaceBindings을 만들었지 만, 그들은 함께 "체인"때문에, 우리는 우리의 RuleTransformer 클래스에 마지막 하나를 통과해야

+0

XML을 어떻게 생성합니까? – mfirry

+0

실제로 파일에서 오래된 XML을 읽고 scala.xml.transform RewriteRules를 사용하여 수정했습니다. – doub1ejack

답변

0
// 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:nsxmlns: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 속성을 어떻게 직접 추가하지 않고 추가하는지 확인하십시오.