如何编辑具有相同字段名称的 XML 属性
本文关键字:字段 属性 XML 何编辑 编辑 | 更新日期: 2023-09-27 18:25:27
如何编辑或重写整个CustomizedFieldCollection
.有 2 个CustomizedField
。我需要动态编辑CustomizedFiledCollection
。它可以是一个或多个CustomizedField
。 XmlWriter
或XDocument
.
<MainCollection>
<CustomizedFieldCollection>
<CustomizedField>
<Key>Documents Checked</Key>
<DataType>Boolean</DataType>
<Value>false</Value>
</CustomizedField>
<CustomizedField>
<Key>Date Completed</Key>
<DataType>DateTime</DataType>
<Value></Value>
</CustomizedField>
</CustomizedFieldCollection>
</MainCollection>
编辑这就是我到目前为止尝试过的。我现在的问题是如何将自定义节点附加到自定义字段集合。我只是尝试附录来记录。我在YouTube上找到了这段代码。这是向集合添加新节点。
XmlDocument doc=new XmlDocument();
doc.Load("C:''Users''Reynan''Desktop''UDM_TRX_XDC_133.xml");
XmlNode customizedNode = doc.CreateElement("CustomizedField");
XmlNode keyNode = doc.CreateElement("Key");
XmlNode dataNode = doc.CreateElement("DataType");
XmlNode valueNode = doc.CreateElement("Value");
keyNode.InnerText = "QWE";
dataNode.InnerText = "ASD";
valueNode.InnerText = "ZXC";
customizedNode.AppendChild(keyNode);
customizedNode.AppendChild(dataNode);
customizedNode.AppendChild(valueNode);
doc.AppendChild(customizedNode);
doc.Save("C:''Users''Reynan''Desktop''UDM_TRX_XDC_133.xml");
我使用以下技术来解析我的 XML 文件:
XmlDocument xd = new XmlDocument();
xd.Load(filename);
XmlNodeList nodelist = xd.SelectNodes("/CustomizedFieldCollection"); // getFieldCollection
foreach (XmlNode node in nodelist) // foreach Field
{
//Now you just look at the attributes of this XmlNode.
// node.Attributes is useful
//XmlNodeList fields = node.SelectNodes("CustomizedField") might also be fun
// The following pattern might also be useful
// XmlNode xN = db.Attributes.GetNamedItem("Key");
// if (xN != null)
}
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication59
{
class Program
{
static void Main(string[] args)
{
string xml =
"<CustomizedFieldCollection>" +
"<CustomizedField>" +
"<Key>Documents Checked</Key>" +
"<DataType>Boolean</DataType>" +
"<Value>false</Value>" +
"</CustomizedField>" +
"<CustomizedField>" +
"<Key>Date Completed</Key>" +
"<DataType>DateTime</DataType>" +
"<Value></Value>" +
"</CustomizedField>" +
"</CustomizedFieldCollection>";
XElement element = XElement.Parse(xml);
XElement newField = new XElement("CustomizedField", new XElement[] {
new XElement("key", "Documents Checked"),
new XElement("DataType", "Boolean"),
new XElement("Value", "false")
});
element.Add(newField);
}
}
}