E4X: grab nodes with namespaces?

后端 未结 3 1633
慢半拍i
慢半拍i 2020-12-18 09:49

I want to learn how to process XML with namespaces in E4X so basically here is what I want to learn, say I have some XML like this:



        
相关标签:
3条回答
  • 2020-12-18 10:38

    If you don't know the namespace you have to deal with there are a variety of methods you can use.

    node.namespace().prefix     //returns prefix i.e. rdf
    node.namespace().uri        //returns uri of prefix i.e. http://www.w3.org/1999/02/22-rdf-syntax-ns#
    
    node.inScopeNamespaces()   //returns all inscope namespace as an associative array like above
    
    //returns all nodes in an xml doc that use the namespace
    var nsElement:Namespace = new Namespace(node.namespace().prefix, 
    node.namespace().uri);
    
    var usageCount:XMLList = node..nsElement::*;
    

    your best bet is to just play around with it. But i do like the prediate logic statement to filter the xml make it much easier to work with.

    hope this give you some ideas to dynamically handle namespaces

    regards,

    Jon

    0 讨论(0)
  • 2020-12-18 10:40

    If you have a XML that contains multiple names but you don't care about the namespaces when getting values from the XML you can do the following....

    Example XML

    <ns1:Item>
      <ns1:ItemType>Printed Material</ns1:ItemType>
      <ns2:Book isbn="123456">
        <ns2:Author>
          <ns2:FirstName>James</ns2:FirstName>
          <ns2:LastName>Smith</ns2:LastName>
        </ns2:Author>
        <ns2:Title>The Book Title</ns2:Title>
      </ns2:Book>
    <ns1:Item> 
    

    You could get any item regardless of namespace like this

    var itemType:String = xml.*::ItemType;
    var bookISBN:Number = xml.*::Book.@isbn;
    var bookTitle:String = xml.*::Book.Title;
    
    0 讨论(0)
  • 2020-12-18 10:47

    I'm not sure whether this answers the question exactly, but given your scenario, the following code retrieves both values (given the "xml" variable, referenced below, is an XML object containing the snippet of XML code you provided):

    // Your "rdf" namespace
    namespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
    use namespace rdf;
    
    // Your "reg" (i.e, default) namespace
    namespace reg = "http://purl.org/rss/1.0/";
    use namespace reg;
    
    private function getYourValues():void
    {               
        var rdfitems:String = xml.rdf::item.@value;
        var regitems:String = xml.reg::item.@value;
    }
    

    A distinction needs to be made between the "rdf" item and the "non-rdf" one, since their element names are otherwise identical, so the second namespace is declared to allow you to retrieve each item independently. Hope it helps!

    0 讨论(0)
提交回复
热议问题