这真的是一个由两部分组成的问题...
我有一个从内存流创建的 XmlReader 对象。我已经使用 .Read() 方法几次,现在我想回到开头并从声明节点重新开始。我该怎么做?
在创建 XmlReader 对象时,我创建了一个 XmlDocument 对象和一个 MemoryStream 对象。在使用内存流创建 XmlReader 之后,是否需要以某种方式销毁这些对象?还是销毁它们也会影响 XmlReader 对象?
这就是我创建 XmlReader 对象的方式
XmlReader xmlReader = null;
XmlDocument doc = new XmlDocument();
doc.Load(m_sXMLPath);
if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
{
XmlDeclaration dec = null;
byte[] bytes = null;
MemoryStream ms = null;
dec = (XmlDeclaration)doc.FirstChild;
switch (dec.Encoding.ToLower())
{
case "utf-8":
bytes = Encoding.UTF8.GetBytes(File.ReadAllText(m_sXMLPath));
break;
case "utf-16":
bytes = Encoding.Unicode.GetBytes(File.ReadAllText(m_sXMLPath));
break;
default:
throw new XmlException("");
}
if (bytes != null)
{
ms = new MemoryStream(bytes);
xmlReader = XmlReader.Create(ms);
}
}
最佳答案
您不能将 XmlReader
对象重新启动到开头。根据 Microsoft 的文档:
XmlReader provides forward-only, read-only access to a stream of XML data. The XmlReader class conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations. http://msdn.microsoft.com/en-us/library/System.Xml.XmlReader.aspx
如果出于某种原因您确实需要回到开头,您应该使用您的 XmlReader
加载一个 XDocument
对象。然后,您可以使用 XDocument
对象来查询 XML 的任何部分。此外,您应该将基于 Stream 的对象包装在 using
block 中,这样您就不必担心破坏。示例如下:
XDocument myXmlDoc;
using(MemoryStream ms = new MemoryStream(bytes))
{
using(XmlReader xmlReader = XmlReader.Create(ms))
{
myXmlDoc = XDocument.Load(xmlReader);
//query your XDocument here to your heart's desire here in any order you want
}
}
如果您不熟悉 LINQ to XML,请查看文档 here
如果您不想使用 XDocument
并坚持使用 XmlDocument
,您也可以使用它(无需查询)来重新遍历您的 XML 文档。无论哪种方式,您都不需要在使用完 XmlDocument
(或 XDocument
)后处理它,因为它不是一次性对象。
关于c# - 使用 XmlReader 如何在开始时重新启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19302716/