簡體   English   中英

XmlReader保持xml文件打開?

[英]XmlReader leaving xml file open?

我有一個看起來像這樣的XML文件:

<Paths>
    <Path>
        <Other stuff be here/>
    </Path>
</Paths>

我想以編程方式在當前節點之后仍在“ Paths”節點內添加一個新的“ Path”節點。 這是我正在嘗試的:

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);

我最終得到一個例外:

“該進程無法訪問該文件,因為它正在被另一個進程使用。”

這發生在xmlDoc.Save行上。 顯然,閱讀器仍處於打開狀態,我無法弄清楚在保存之前如何關閉閱讀器。

我試過你編碼是正確的。 但是您的XML不是,結尾應該是關閉<Paths>元素而不是<Path>

<Paths>
    <Path>
        <!-- Other stuff be here -->
    </Path>
</Paths>

另外,請確保該文件確實未在其他進程中使用。 您可以使用流程瀏覽器工具找到它。 http://windowsxp.mvps.org/processlock.htm

結果XML:

<Paths>
    <Path>
        <!-- Other stuff be here -->
    </Path>
    <Path xmlns="Test" />
</Paths>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM