修改存储在媒体库中的XML
本文关键字:XML 媒体库 存储 修改 | 更新日期: 2023-09-27 18:13:53
mi问题是这样的,我在媒体库中有一个XML,我需要修改一些东西,但流是只读的,有什么想法吗?
我的代码 string nodeId = string.Empty;
List<XmlNode> nodes = GetAll(); // Get all the nodes in my XML
foreach (XmlNode node in nodes)
{
nodeId = node.SelectSingleNode(".//id").InnerText;
if (nodeId == id) // id the id of the node that i'm looking for
{
node.ParentNode.RemoveChild(node);
node.OwnerDocument.Save(MediaManager.GetMedia(mitem).GetStream().Stream);
return;
}
}
你只是想保存文档,就像你在磁盘上保存文件一样,你需要上传修改后的流回媒体库:
http://briancaos.wordpress.com/2009/07/09/adding-a-file-to-the-sitecore-media-library-programatically/记住,本质上你是在上传一个新文档,而不是修改一个已有的文档。
下面是一些示例代码,用于从媒体库检索XML文档,添加新节点并将其保存回相同位置。
string mediaItemPath = "/sitecore/media library/Files/TestDoc";
string fileName = "TestDoc.xml";
//get the content db, i.e. master db
Sitecore.Data.Database contentDB = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
//get the media file
MediaItem mi = contentDB.GetItem(mediaItemPath);
if (mi == null)
throw new ItemNotFoundException(mediaItemPath);
if (!mi.Extension.Equals("xml") || !mi.MimeType.Equals("text/xml"))
throw new MediaException(string.Format("File {0} was not of correct XML format", mediaItemPath));
//load xml document using media stream
var xDoc = System.Xml.Linq.XDocument.Load(mi.GetMediaStream());
////manipulate the xml as required
////-- update or add new node or whatever
string nodeName = "Item";
string nodeValue = string.Format("{0} {1}", "test node ", DateTime.Now.ToString("yyyyMMddhhmmss"));
xDoc.Element("rootNode")
.Add(new System.Xml.Linq.XElement(nodeName, nodeValue));
//save the modified document into a stream
var xmlStream = new System.IO.MemoryStream();
xDoc.Save(xmlStream);
// Create the options
var options = new Sitecore.Resources.Media.MediaCreatorOptions
{
FileBased = false, // Store the file in the database, not as a file
IncludeExtensionInItemName = false, // Keep file extension in item name
KeepExisting = false, // Keep any existing file with the same name
Versioned = false, // Do not make a versioned template
Destination = mediaItemPath, // set the path
Database = contentDB // Set the database
};
//Use a security disabler to allow changes
using (new Sitecore.SecurityModel.SecurityDisabler())
{
//save the item back into media library
Item mediaItem = Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(xmlStream, fileName, options);
xmlStream.Dispose();
}