C# を使用して、XML ファイル内の要素の属性を変更するにはどうすればよいですか?
133729 次
4 に答える
73
マイク; XMLドキュメントを変更する必要があるときはいつでも、次のように作業します。
//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlFile);
//xmlFile is the path of your file to be modified
お役に立てば幸いです
于 2008-12-15T10:40:18.367 に答える
63
フレームワーク 3.5 を使用している場合は、LINQ to xml を使用します。
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
于 2008-12-15T08:31:31.840 に答える
14
変更する属性が存在しないか、誤って削除された場合、例外が発生します。最初に新しい属性を作成し、次のような関数に送信することをお勧めします。
private void SetAttrSafe(XmlNode node,params XmlAttribute[] attrList)
{
foreach (var attr in attrList)
{
if (node.Attributes[attr.Name] != null)
{
node.Attributes[attr.Name].Value = attr.Value;
}
else
{
node.Attributes.Append(attr);
}
}
}
使用法:
XmlAttribute attr = dom.CreateAttribute("name");
attr.Value = value;
SetAttrSafe(node, attr);
于 2015-01-06T14:47:45.323 に答える