开发者

How to retrieve values from an Xml as Objects but not Strings?

开发者 https://www.devze.com 2023-02-14 08:51 出处:网络
I have some code that parses an xml file using XDocument. It retrieves the values correctly but some of the values I save t开发者_如何学编程o xml is of type Object. So when I read these values from t

I have some code that parses an xml file using XDocument.

It retrieves the values correctly but some of the values I save t开发者_如何学编程o xml is of type Object. So when I read these values from the xml, they come as string values, even though I cast them as objects:

XDocument doc = XDocument.Load ( file );
XElement xe = doc.Element ( "EffectFile" );

xe.Elements ( "Options" ).Any ( )
    ? xe.Elements ( "Options" ).Select (
        o => o.Elements ( "Option" ).Select (
            n => ( object ) n.Value ).First ( ) )
    : null ) )

The value as it appears in the xml:

...
<Option>88</Option>
...

comes as "88", instead of Object 88.

I understand that when I cast a string to an Object, it will still be a string, but is there a way to make it an Object of the actual value (whatever that might be) but not a string?

Because these are different, isn't it?:

object value = 88;
object value = (object) "88";

and later when I use my options value stored as object[], I want to be able to do:

int intValue = (int) value;


XML holds strings - if you are sure what you are keeping in what places in your xml, you can parse it to correct type - like Tony Casale wrote for ints.

Or if you can have any objects in some places, you'd have to add attribute which specifies to your xml reading code, to what type this node should be changed after reading.

like this:

<option>
     <name>some name</name>
     <value type="int">123</value>
</option>
<option>
     <name>some other name</name>
     <value type="string">abcdefg</value>
</option>

Then in your code you will have to check which type to convert each string from value tag.


Yes those are different. You need to do:

int intValue = int.Parse("88");

If you don't know what the source type is, you can also do:

int intValue = Convert.ToInt32(someObject);

Which will convert anything to an int, if it can.


XElement has an operator overload for explicit int cast, so you probably should be doing that

XDocument doc = XDocument.Load ( file );
XElement xe = doc.Element ( "EffectFile" );

xe.Elements ( "Options" ).Any ( )
    ? xe.Elements ( "Options" ).Select (
        o => o.Elements ( "Option" ).Select (
            n => ( int) n).First ( ) )
    : null ) )


XML is text... it is normally returns values of nodes as text. As jbtule said you can use explicit casts (see http://msdn.microsoft.com/en-us/library/bb348319.aspx) for details.

You may also consider using XML serialization instead of reading raw XML.

0

精彩评论

暂无评论...
验证码 换一张
取 消