0

我的问题是这样的,我在 Medialibrary 中有一个 XML,我需要修改一些东西,但是 strear 是只读的,有什么想法吗?

我的代码

        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;
            }
        }
4

1 回答 1

2

您只是想像在磁盘上保存文件一样保存文档,您需要将修改后的流上传回媒体库:

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();
}
于 2013-05-16T20:05:20.170 回答