3

I ahve experience serializing/deserializing XML files but I have never had to parse just a single statement, so I'm not sure how to go about this.

I have a string that holds this:

<Vol Model_Type="Flat">102.14</Vol>

And, I want to extract just the 102.14.

Should I use XPath, or is there a simpler option?

0

2 Answers 2

8

If you're using .NET 3.5 or above, use LINQ to XML. For example:

string x = "<Vol Model_Type=\"Flat\">102.14</Vol>";
XElement element = XElement.Parse(x);
decimal value = (decimal) element;

XML handling doesn't get much simpler than that :)

Of course, that's assuming you don't care about the element name or the attribute. If you do, LINQ to XML will still make it easy for you.

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

4 Comments

Seems like just the thing I was looking for. I have using .NET 4.0. However, XElement does not seem to have the Parse property. I added System.Linq namespace. Anyways, thanks for pointing me in the right direction.
@xbonez: You need the System.Xml.Linq namespace, and XElement most definitely does have a Parse method: msdn.microsoft.com/en-us/library/…
Strange. I added references to System.Xml and System.Xml.Linq and added the two namespaces, and get I get an error stating System.Xml.XmlElement' does not contain a definition for 'Parse'
Geez....nevermind. Intellisense autocorrected it to XmlElement instead of XElement. Works now. Thank you.
0
string x = "<Vol Model_Type=\"Flat\">102.14</Vol>";
XElement element = XElement.Parse(x);
decimal value=element.Value.Tostring();

Comments

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.