자바스크립트

자바스크립트 XML파싱

마리오64 2019. 12. 19. 00:00
<script>
        let parser, xmlDoc;
        let text = `<?xml version="1.0" encoding="utf-8"?>
        <layer-list
        xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:bottom="1.0dip">
            <shape shape="rectangle">
                <gradient android:startColor="#ffc6ffdd" android:endColor="#fffbd786" android:angle="45.0" android:centerColor="#fff7797d" />
                <corners android:topLeftRadius="0.0dip" android:topRightRadius="0.0dip" android:bottomLeftRadius="14.0dip" android:bottomRightRadius="14.0dip" />
            </shape>
        </item>
        </layer-list>`

        parser = new DOMParser();
        xmlDoc = parser.parseFromString(text,"text/xml");
        let shapeTag= xmlDoc.getElementsByTagName("shape")[0]
        let shapecolor = xmlDoc.getElementsByTagName("gradient")[0].getAttributeNS("http://schemas.android.com/apk/res/android","startColor")
        console.log(shapeTag)
        console.log(shapecolor)        
</script>

 

 

테마툴을 만드는데 안드로이드 레이아웃 XML 태그를 파싱을 하기위해 가져왔습니다.

XML 스펙에는 네임스페이스가 있어서 태그나 속성에 네임스페이스를 지정할수있습니다.

네임스페이스는 다른 종류의 태그들이 같은이름을 사용할때 충돌하기 때문에 그룹을 따로 짓기위해 씁니다.

DOMParser 객체를 생성하고 parseFromString(text,"text/xml") 형식을 정합니다.

 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

를 보면 네임스페이스로 android를 쓰고 있습니다. 

<item android:bottom="1.0dip"> 네임스페이스:속성이름 ="속성 값"

네임스페이스가 있는 속성은 getAttributeNS(네임스페이스URI,속성)로 값을 읽습니다.