0

I don't know if this is possible or not with just javascript/jquery. I have a number of xml files that I usually read and disply with xpath, but the xml files are structured with HTML elements like this:

 <?xml version="1.0" encoding="UTF-8"?>
 <catalog>
 <outcome>
    <title>1.1</title>
    <section>
    <p>some text as an intro:
      <ul>
        <li>part of list</li>
        <li>part of list</li>
      </ul>
    </p>
    <p>more text</p>
    </section>
</outcome>

<outcome>
 <title>1.2</title>
 <section>
    <p>some text as an intro:
      <ul>
        <li>part of list</li>
        <li>part of list</li>
      </ul>
    </p>
    <p>more text</p>
    </section>
</outcome>
</catalog>

I want to display all children and descendants of a select element. Using javascript, I know how to load the xml and select the element I need, and I know how to loop through nodes, but is it possible just to get a node and its descendants as a string? I could then just take the string and append a div like element.html("string"). I would let my css style the elements as needed. Is this possible with javascript? I know xsl could do this as a whole page, but I need just a small part of a large xml.

1 Answer 1

1

Can do it fairly simply using jQuery by treating it as html

$(function() {
  $.get('data.xml', function(xml) {
    $(xml).find('outcome').each(function() {
      $('body').append($(this).html());
    });
  }, 'html');
});

If you need to manipulate the new html prior to inserting it ( like adding classes etc) that is also failry trivial

DEMO

Sign up to request clarification or add additional context in comments.

4 Comments

that is great - can I filter it by the content of the <title> element. In the example, I only need outcome with the <title> element that contains "1.1". I was trying to use var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null); var serializer = new XMLSerializer(); var str = serializer.serializeToString(xml); alert(str); I was selecting the path to the Title element
can use jQuery methods to filter out what you want. You may also need to use $.parseXML() , seems hard to change out the title to another tag. Internals of jQuery may be treating it as xml doc
I must be doing something wrong. when I filter by title, I only get the contents of the title element, none of the children. Hmm
right, have to look back up to the outcome when you find the right title, can just use parent()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.