从SonosparsingXML

我试图parsing从Sonos订阅的XML输出我在Node.js这样做我已经尝试了两个不同的npm模块,xml2js和libxmljs,但我似乎无法正确。 我find的所有例子都是一个简单的XML,但是我正在尝试parsing一个更高级的文件,当你知道如何处理它时可能并不难。

我希望有人能帮助我,让我明白如何处理这样的文件。 在我的例子中,然后我想要22的值:

<Volume channel="Master" val="22"/> 

这是XML文件

 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0"> <e:property> <LastChange> <Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/"> <InstanceID val="0"> <Volume channel="Master" val="22"/> <Volume channel="LF" val="100"/> <Volume channel="RF" val="100"/> <Mute channel="Master" val="0"/> <Mute channel="LF" val="0"/> <Mute channel="RF" val="0"/> <Bass val="0"/> <Treble val="0"/> <Loudness channel="Master" val="1"/> <OutputFixed val="0"/> <HeadphoneConnected val="0"/> <SpeakerSize val="5"/> <SubGain val="0"/> <SubCrossover val="0"/> <SubPolarity val="0"/> <SubEnabled val="1"/> <SonarEnabled val="0"/> <SonarCalibrationAvailable val="0"/> <PresetNameList val="FactoryDefaults"/> </InstanceID> </Event> </LastChange> </e:property> 

谢谢。

试试这个代码:

 var DOMParser = require('xmldom').DOMParser; var xmltext = `<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0"> <e:property> <LastChange> <Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/"> <InstanceID val="0"> <Volume channel="Master" val="22"/> <Volume channel="LF" val="100"/> <Volume channel="RF" val="100"/> <Mute channel="Master" val="0"/> <Mute channel="LF" val="0"/> <Mute channel="RF" val="0"/> <Bass val="0"/> <Treble val="0"/> <Loudness channel="Master" val="1"/> <OutputFixed val="0"/> <HeadphoneConnected val="0"/> <SpeakerSize val="5"/> <SubGain val="0"/> <SubCrossover val="0"/> <SubPolarity val="0"/> <SubEnabled val="1"/> <SonarEnabled val="0"/> <SonarCalibrationAvailable val="0"/> <PresetNameList val="FactoryDefaults"/> </InstanceID> </Event> </LastChange> </e:property> </e:propertyset>`; var doc = new DOMParser().parseFromString( xmltext, "application/xml" ); var docElem = doc.documentElement; var Volume = docElem.getElementsByTagName('Volume'); //console.log(Volume.toString()); //Volume.length; //3 console.log(Volume[0].getAttribute("val")); //'22' console.log(Volume[0].getAttribute("channel")); //'Master'