1

Below is a string I pull from DB. I need to only pull the 'My Title' text from it. However, this value is different for every entry, so I can't use substring, like str.substring(1,4). The xml around it stays the same.

What's the best way to pull 'My Title'?

<?xml version='1.0' encoding='UTF-8'?><root available-locales="en_US" default-locale="en_US"><Title language-id="en_US">My Title</Title></root>

Thanks!

1 Answers1

3

Use the DOMParser(). This is more elegant than any solution involving RegEx, read this post about the issue with XML/HTML and RegEx

let data = '<?xml version="1.0" encoding="UTF-8"?><root available-locales="en_US" default-locale="en_US"><Title language-id="en_US">My Title</Title></root>';

let parser = new DOMParser();
let xmlDoc = parser.parseFromString(data,"text/xml");

let title = xmlDoc.getElementsByTagName("Title")[0].innerHTML;

console.log(title)
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • Deleted mine, this is definitely the way to go. – Máté Safranka Apr 23 '18 at 15:26
  • @MátéSafranka While I don't think parsing HTML with regular expressions is a good idea, in this case your answer was appropriate. – Matus Dubrava Apr 23 '18 at 15:42
  • 1
    @MatusDubrava The reason I retracted it is because I don't know how complicated the OP's XML really is or will become in the future. I actually started wording a massive caveat saying that "regexes can work in this particular case if it really is as simple as your example", but then I just thought I'd rather not encourage this type of solution because it's so dependent on the specifics of the use case. If someone asks a question on SO I personally prefer to give them solutions they can safely apply in the future as well. The solution I posted might work to day but it can easily break tomorrow. – Máté Safranka Apr 23 '18 at 15:47
  • 1
    Hi Luca, yes this solved my problem. This was definitely the best way to go. Thanks! – dukenukem6487 Apr 23 '18 at 18:51
  • Sure, glad, I could help! – Luca Kiebel Apr 23 '18 at 18:53