سؤال

I'm getting a "Property 'InnerText' is WriteOnly" error when trying to read an attribute value

Here's my XML:

<?xml version="1.0" encoding="utf-8"?>
<products>
    <product ID="11837">
        <price currency="EUR">75.29</price>
        <properties>
            <property name="brand">
                <value></value>
            </property>
    </properties>
<variations/>
</product>
</products>

To extract the price I do:

node.SelectSingleNode("price").InnerText

which returns "75.29"

But when I do:

node.Attributes("ID").InnerText

I get the error:

Property 'InnerText' is WriteOnly

I don't see any reason why it's write-only and don't know how I can change it so I can read the value.

هل كانت مفيدة؟

المحلول

It's a fact of the implementation of XmlAttribute that it only supports writing to its InnerText property. You don't "change it" so that you can read the value - you use the Value property:

Gets or sets the value of the node.

Alternatively, you can access the value via InnerText if you cast the XmlAttribute as an XmlNode (its base class).

نصائح أخرى

According to the MSDN:

The concatenated values of the node and all its children. For attribute nodes, this property has the same functionality as the Value property.

You should just use the Value property, instead, like this:

node.Attributes("ID").Value

Or you can cast it to an XmlNode and then access the InnerText. XmlNode is the base class for XmlAttribute, and its InnerText property is read-write rather than write-only. For instance:

CType(node.Attributes("ID"), XmlNode).InnerText

I'm not sure why it's write-only in the XmlAttribute class. Presumably there must have been some good reason for it, given the internal workings of the class, though it's hard to imagine what that would be. The odd thing is that in the MSDN documentation in version 1.1 actually says that it is a read/write property in that version of the framework. Then, in versions 2.0 - 4.0 it defines the property as write-only, but the description of it says "Gets or sets..." So, the MSDN hasn't exactly been consistent about it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top