XmlReader 使 xml 文件处于打开状态?
XmlReader leaving xml file open?
我有一个 XML 文件,看起来有点像这样:
<Paths>
<Path>
<Other stuff be here/>
</Path>
</Paths>
我想以编程方式在当前节点之后添加一个新的 "Path" 节点,但仍在 "Paths" 节点内。这是我正在尝试的:
XmlDocument xmlDoc = new XmlDocument();
string xmlFilePath = "ThatFileFromAbove.xml";
using (XmlReader reader = XmlReader.Create(xmlFilePath))
xmlDoc.Load(reader);
XmlNode newPathNode = xmlDoc.CreateNode(XmlNodeType.Element, "Path", "Test");
xmlDoc.GetElementsByTagName("Paths")[0]
.InsertAfter(newPathNode, xmlDoc.GetElementsByTagName("Paths")[0].LastChild);
xmlDoc.Save(xmlFilePath);
我最终遇到异常:
"The process cannot access the file because it is being used by another process."
这发生在 xmlDoc.Save
行。显然 reader 仍然打开,我不知道如何在保存前关闭 reader。
我试过你的代码是正确的。但是你的 XML 不是,最后应该关闭 <Paths>
元素而不是 <Path>
<Paths>
<Path>
<!-- Other stuff be here -->
</Path>
</Paths>
还要确保该文件确实未在其他进程中使用。
您可以使用 Process Explorer 工具来找出它。 (http://windowsxp.mvps.org/processlock.htm)
结果XML:
<Paths>
<Path>
<!-- Other stuff be here -->
</Path>
<Path xmlns="Test" />
</Paths>
我有一个 XML 文件,看起来有点像这样:
<Paths>
<Path>
<Other stuff be here/>
</Path>
</Paths>
我想以编程方式在当前节点之后添加一个新的 "Path" 节点,但仍在 "Paths" 节点内。这是我正在尝试的:
XmlDocument xmlDoc = new XmlDocument();
string xmlFilePath = "ThatFileFromAbove.xml";
using (XmlReader reader = XmlReader.Create(xmlFilePath))
xmlDoc.Load(reader);
XmlNode newPathNode = xmlDoc.CreateNode(XmlNodeType.Element, "Path", "Test");
xmlDoc.GetElementsByTagName("Paths")[0]
.InsertAfter(newPathNode, xmlDoc.GetElementsByTagName("Paths")[0].LastChild);
xmlDoc.Save(xmlFilePath);
我最终遇到异常:
"The process cannot access the file because it is being used by another process."
这发生在 xmlDoc.Save
行。显然 reader 仍然打开,我不知道如何在保存前关闭 reader。
我试过你的代码是正确的。但是你的 XML 不是,最后应该关闭 <Paths>
元素而不是 <Path>
<Paths>
<Path>
<!-- Other stuff be here -->
</Path>
</Paths>
还要确保该文件确实未在其他进程中使用。 您可以使用 Process Explorer 工具来找出它。 (http://windowsxp.mvps.org/processlock.htm)
结果XML:
<Paths>
<Path>
<!-- Other stuff be here -->
</Path>
<Path xmlns="Test" />
</Paths>