[英]How to modify existing XML file with XmlDocument and XmlNode in C#
[英]Cannot modify XML File with XmlDocument and FileStream in C#
我正在创建 html 页面的小型构造函数,我正在使用 XML
当我必须在 xml 中编辑特定元素时,它不起作用:
private string current_element = "pole";
private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
XmlDocument xmlData = new XmlDocument();
FileStream fs = new FileStream(ConstructorEngine.global + "/FormData.xml", FileMode.Open, FileAccess.ReadWrite);
xmlData.Load(fs);
var body = xmlData.GetElementsByTagName("Body")[0];
foreach (XmlNode child in body.ChildNodes)
{
if(child.Attributes["c_id"].Value == currentElement)
{
if(e.ChangedItem.Label == "Text")
{
child.InnerText = e.ChangedItem.Value.ToString();
}
}
}
fs.Close();
}
没有给出错误,但文件没有改变
我的 XML:
<?xml version="1.0" encoding="utf-8"?>
<FormData>
<title>Constructor 1</title>
<Body xmlns:xi="http://www.w3.org/2001/XInclude" id="app" width="400" height="400">
<Button position="absolute" c_id="New_Btn" top="331" left="3" width="75" height="50" background-color="white" color="black" font-size="8,25" font-family="[FontFamily: Name=Microsoft Sans Serif]" border="1" border-color="0">Changed Button</Button>
<Text position="absolute" c_id="pole" top="433" left="157" width="100" height="50" background-color="white" color="black" font-size="8,25" font-family="[FontFamily: Name=Microsoft Sans Serif]" border="1px solid;" border-color="black">pole</Text>
</Body>
<footer id="footer">Created By Constructor 1</footer>
</FormData>
XmlDocument
在加载后不会保留与原始文件的关系。 要解决这种情况:
FileStream
(理想情况下,通过在using 语句中加载 XmlDocument,该语句在 scope 完成时隐式关闭和处置。在此 scope 之外声明 XmlDocument 变量。Save
方法。 出于您的目的,将要保存到的文件的名称传递给它就足够了。使用 xml linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement text = doc.Descendants().Where(x => x.Name.LocalName == "Text").FirstOrDefault();
text.Attribute("c_id").SetValue("abc");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.