簡體   English   中英

XDocument 如何加載/修改/關閉

[英]XDocument how to load/modify/Close

這已經被問過很多次(就像這里)並且沒有一個解決方案針對 .NET Core 5

我正在嘗試加載、修改和保存 XML 文檔,這應該是小菜一碟。

但事實並非如此,因為您無法保存加載操作后仍處於打開狀態的文檔。

以下是我這樣做的方式:

XDocument doc = XDocument.Load(path);
var xmlns = doc.Root.GetDefaultNamespace();
var xlinkns = doc.Root.GetNamespaceOfPrefix("xlink");

// Add the circle
doc.Root.Add(new XElement(xmlns + "circle",
    new XAttribute("stroke", "blue"),
    new XAttribute("stroke-width", "3"),
    new XAttribute("cx", $"{beaconXPositionOnMapInPt.ToString(CultureInfo.InvariantCulture)}"),
    new XAttribute("cy", $"{beaconYPositionOnMapInPt.ToString(CultureInfo.InvariantCulture)}"),
    new XAttribute("r", $"{radiusInPoint.ToString(CultureInfo.InvariantCulture)}"),
    new XAttribute("fill-opacity", "0.1")
    ));

// Add the beacon image
//XNamespace xlinkns = "https://www.w3.org/1999/xlink";
doc.Root.Add(new XElement(xmlns + "image",
    new XAttribute("x", $"{beaconXPositionOnMapInPt.ToString(CultureInfo.InvariantCulture)}"),
    new XAttribute("y", $"{yPos.ToString(CultureInfo.InvariantCulture)}"),
    new XAttribute(xlinkns + "href", $"data:image/{iconFormat};base64,{icon}")
    ));

doc.Save(path);

上面的這個拋出: System.IO.IOException :'進程無法訪問文件'D:\ blablabla.SVG',因為它正在被另一個進程使用。

XDocument.Load(string path) 似乎沒有關閉文件。

編輯:只是為了清楚並證明我沒有在其他任何地方打開文件。 這是運行我的單元測試之前的屏幕截圖: 在此處輸入圖像描述

這是加載語句后應該關閉文件的捕獲。 它仍然由測試主機打開。 在此處輸入圖像描述

我使用 Process Explorer 來跟蹤文件句柄。

這沒有在我的問題中顯示,但我在上面代碼之前的同一個文件上錯誤地使用了 XmlTextReader。

我的錯。

暫無
暫無

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

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