I have a string :
responsestring = "<?xml version="1.0" encoding="utf-8"?>
<upload><image><name></name><hash>SOmetext</hash>"
How can i get the value between
<hash> and </hash>
?
My attempts :
responseString.Substring(responseString.LastIndexOf("<hash>") + 6, 8); // this sort of works , but won't work in every situation.
also tried messing around with xmlreader , but couldn’t find the solution.
ty
Others have suggested LINQ to XML solutions, which is what I’d use as well, if possible.
If you’re stuck with .NET 2.0, use
XmlDocumentor evenXmlReader.But don’t try to manipulate the raw string yourself using
SubstringandIndexOf. Use an XML API of some description. Otherwise you will get it wrong. It’s a matter of using the right tool for the job. Parsing XML properly is a significant chunk of work – work that’s already been done.Now, just to make this a full answer, here’s a short but complete program using your sample data:
Obviously that will loop over all the
hashelements. If you only want one, you could usedoc.Descendants("hash").Single()ordoc.Descendants("hash").First()depending on your requirements.Note that both the conversion I’ve used here and the
Valueproperty will return the concatenation of all text nodes within the element. Hopefully that’s okay for you – or you could get just the first text node which is a direct child if necessary.