使用XPath实现IXmlSerializable ReadXml()的最佳方法 [英] Best way to implement IXmlSerializable ReadXml() using XPath
问题描述
我正在实现IXmlSerializable的ReadXml()方法,我认为使用XPath可能是实现此目的的最好方法.
I'm implementing the ReadXml() method of IXmlSerializable and I figure using XPath is probably the nicest way to do this.
但是,ReadXml()需要正确处理阅读器的位置.
However, ReadXml() needs to handle the reader position properly.
因此,考虑到我的WriteXml()会生成如下内容:
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 */
}
}
推荐答案
我怀疑如果常规使用该方法,可能会遇到一些性能问题.由于您的xml相对简单,我强烈怀疑您直接使用 XmlReader
会更好.
I suspect you might run into some performance issues if using that approach routinely. Since your xml is relatively simple, I strongly suspect that you would do better just using XmlReader
directly...
...但是这样做并不容易;IMO,最好避免实施 IXmlSerializable
(使用常规集合属性等突出显示)-这是导致错误和沮丧的常见原因.
...but doing so isn't easy; IMO, it is better to try to avoid the need to implement IXmlSerializable
(juts using regular collection properties etc) - it is a common cause of bugs and frustration.
这篇关于使用XPath实现IXmlSerializable ReadXml()的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!