Hi,
I'm implementing the ReadXml() method of IXmlSerializable and I figure using XPath is probably the nicest way to do this.
However, ReadXml() needs to handle the reader position properly.
So given that my WriteXml() produces something like this:
<ObjectName>
<SubNode>2</SubNode>
<SubNode>2</SubNode>
</ObjectName>
Is there a better way than (this terrible way) below to ensure the Reader is correctly positioned afterwards?
public override void ReadXml(System.Xml.XmlReader reader)
{
reader.Read(); /* Read Opening tag */
/* Using reader.ReadStartElement("ObjectName") reads forward a node,
i.e. current node becomes the first <SubNode>
whereas Read() doesn't even when the documentation says they both do
*/
XPathNavigator n = MakeXPathNavigator(reader.ReadSubtree());
XPathNodeIterator nodes = n.Select(".//SubNode");
while (nodes.MoveNext())
{
/* Do stuff with nodes */
_values.Add(nodes.Current.ValueAsInt);
}
reader.Skip(); /* Skip reader forward */
}
public static XPathNavigator MakeXPathNavigator(XmlReader reader)
{
try
{
return new XPathDocument(reader).CreateNavigator();
}
catch(XmlException e)
{
throw e; /* Maybe hide/deal with exception */
}
}