无法保存对存储在Sharepoint 2010文档库中的XML文档的更改
本文关键字:文档 XML 2010 保存 存储 Sharepoint | 更新日期: 2023-09-27 18:11:05
我正在进行一个项目,该项目需要将所有SQL连接和查询信息存储在XML文件中。为了使我的项目可配置,我试图创建一种方法,让用户通过一系列文本框配置他的sql连接字符串信息(数据源,目录,用户名和密码)。然后将此输入保存到SQL文档中的适当节点。
我可以从XML文件中获得当前信息,并在文本框中显示该信息,以供用户查看和更正,但是在保存更改时遇到了一个错误。
下面是我用来更新和保存xml文档的代码。
protected void submitBtn_Click(object sender, EventArgs e)
{
SPFile file = methods.web.GetFile("MyXMLFile.xml");
myDoc = new XmlDocument();
byte[] bites = file.OpenBinary();
Stream strm1 = new MemoryStream(bites);
myDoc.Load(strm1);
XmlNode node;
node = myDoc.DocumentElement;
foreach (XmlNode node1 in node.ChildNodes)
{
foreach (XmlNode node2 in node1.ChildNodes)
{
if (node2.Name == "name1")
{
if (node2.InnerText != box1.Text)
{
}
}
if (node2.Name == "name2")
{
if (node2.InnerText != box2.Text)
{
}
}
if (node2.Name == "name3")
{
if (node2.InnerText != box3.Text)
{
node2.InnerText = box3.Text;
}
}
if (node2.Name == "name4")
{
if (node2.InnerText != box4.Text)
{
}
}
}
}
myDoc.Save(strm1);
}
此时大多数条件都是空的,因为我还在测试。
正如我所说,直到最后一行代码都运行良好。在这一点上,我得到错误"内存流是不可扩展的。"我知道使用内存流来更新存储的文件是不正确的,但是我不能找出正确的方法来做到这一点。
我试图实现在内存流类似问题中给出的解决方案是不可扩展的,但这种情况与我的不同,因此实现对我没有意义。如能澄清,将不胜感激。
使用以字节数组为参数的MemoryStream
构造函数创建MemoryStream
的不可调整大小的实例。由于您正在对文件(以及底层字节)进行更改,因此需要一个可调整大小的MemoryStream
。这可以通过使用MemoryStream
类的无参数构造函数并将字节数组写入MemoryStream
来实现。
试试这个:
SPFile file = methods.web.GetFile("MyXMLFile.xml");
myDoc = new XmlDocument();
byte[] bites = file.OpenBinary();
using(MemoryStream strm1 = new MemoryStream()){
strm1.Write(bites, 0, (int)bites.Length);
strm1.Position = 0;
myDoc.Load(strm1);
// all of your edits to the file here
strm1.Position = 0;
// save the file back to disk
using(var fs = new FileStream("FILEPATH",FileMode.Create,FileAccess.ReadWrite)){
myDoc.Save(fs);
}
}
要获得Sharepoint文件的FILEPATH
,它将沿着这些行(我现在没有设置Sharepoint开发环境):
SPFile file = methods.web.GetFile("MyXMLFile.xml")
var filepath = file.ParentFolder.ServerRelativeUrl + "''" + file.Name;
或者像这样使用SPFile
类的SaveBinary
方法可能更容易:
// same code from above
// all of your edits to the file here
strm1.Position = 0;
// don't use a FileStream, just SaveBinary
file.SaveBinary(strm1);
我没有测试这段代码,但我已经在Sharepoint解决方案中使用它来修改Sharepoint列表中的XML(主要是OpenXML)文档。阅读这篇博文了解更多信息
您可以考虑使用XDocument类而不是XmlDocument类。http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx
我更喜欢它,因为它简单,而且它不必使用内存流。
编辑:您可以像这样添加到文件:
XDocument doc = XDocument.Load('filePath');
doc.Root.Add(
new XElement("An Element Name",
new XAttribute("An Attribute", "Some Value"),
new XElement("Nested Element", "Inner Text"))
);
doc.Save(filePath);
或者你可以搜索一个元素并像这样更新:
doc.Root.Elements("The element").First(m =>
m.Attribute("An Attribute").Value == "Some value to match").SetElementValue(
"The element to change", "Value to set element to");
doc.Save('filePath');