如何在Excel 2010/2013中修改自定义XML部件 [英] How to modify Custom XML parts in Excel 2010/2013
问题描述
我试图弄清楚如何修改预先保存在Excel中的自定义XML部件.到目前为止,我发现的所有Web资源都介绍了如何在Excel中添加自定义XML部件.这我已经知道了.但是我想修改现有零件.
I am trying to figure out how to modify custom XML parts previusly saved in Excel. All the web resources I have found so far explain how to add custom XML parts in Excel. This I already know. But I want to modify existing parts.
API似乎只有Add方法.如果再次调用Add方法,则会添加其他XML部分.
The API seems to have only Add method. If Add method is called again it adds additional XML parts.
我使用以下代码保存我的自定义XML
I use the following code to save my custom XML
XNamespace NS = "http://schema.blabla.com";
var xDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "no"),
new XComment("Custom XML Parts demo"),
new XElement(NS + "demo",
new XElement(NS + "config",
new XElement(NS + "property",
new XAttribute("value", "myVlaue",
new XAttribute("key", "myKey"))))));
Office.CustomXMLPart customXMLPart = workbook.CustomXMLParts.Add(xDoc.ToString(), System.Type.Missing);
我使用以下代码检索我的自定义XML
I use the following code to retrieve my custom XML
var retrievedXMLParts = workbook.CustomXMLParts.SelectByNamespace(NS.NamespaceName);
//FirstOrDefault always returns first saved data, LastOrDefault needs to be called to get the latest
//var customXMLPart = retrievedXMLParts.Cast<CustomXMLPart>().FirstOrDefault();
var customXMLPart = retrievedXMLParts.Cast<CustomXMLPart>().LastOrDefault();
var propertiesXML = customXMLPart != null ? customXMLPart.XML : String.Empty;
我想要实现的是检查自定义XML是否存在,更新其内容,而不是将其添加为重复内容
What I would like to achieve is to check if a custom XML exists update its content instead off adding it as duplicate
推荐答案
我想我已经找到了一种解决方案,但是它涉及遍历所有自定义XML部分,删除要更新的部分,然后再次添加:
I think I have found a solution but it involves iterating through all the custom XML parts, deleting the one you want to update and then add again:
IEnumerator e = workbook.CustomXMLParts.GetEnumerator();
CustomXMLPart p;
while (e.MoveNext())
{
p = (CustomXMLPart) e.Current;
//p.BuiltIn will be true for internal buildin excel parts
if (p != null && !p.BuiltIn && p.NamespaceURI == NS.NamespaceName)
p.Delete();
}
这篇关于如何在Excel 2010/2013中修改自定义XML部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!