【发布时间】:2018-02-15 17:11:12
【问题描述】:
我有一个现有的 XML 文件,我想更新它的一些属性。我用谷歌搜索了很多类似的问题和答案,但我没有运气。
<?xml version="1.0"?>
<system ExportDate="2/15/2018" ExportTime="11:56 AM EST" DateFormat="MM/dd/yyyy" NumberFormat="HH:mm:ss " SchemaValidation="true" ExportVersion="2016.1.SP1710.57 [Build 82] - 27 September 2017 (01:30 IST)" xmlns="http://www.mentor.com/harness/Schema/LibrarySchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mentor.com/harness/Schema/LibrarySchema file:/C:/MentorGraphics/VeSys_Client/dtd/LibrarySchema.xsd" XMLVersion="1.6">
<librarymaterial librarymaterial_id="XXX" description="YYY" materialcode="ZZZ" />
</system>
我正在尝试为某些属性设置新值。
对于root,我没有问题
xmlDoc.DocumentElement.SetAttribute("ExportDate", DateTime.Now.ToShortDateString());
xmlDoc.DocumentElement.SetAttribute("ExportTime", DateTime.Now.ToShortTimeString() + " EST");
但是,当我尝试不同的方法但没有希望时
方法一:
XmlNode node = xmlDoc.SelectSingleNode("/system/librarymaterial");
node.Attributes["librarymaterial_id"].Value=_librarymaterial_id;
错误:
System.NullReferenceException: '对象引用未设置为对象的实例。'
节点为空。
方法二:
var nodes = xmlDoc.SelectNodes("/system/librarymaterial");
foreach (XmlElement n in nodes)
{
n.SetAttribute("librarymaterial_id", _librarymaterial_id);
}
这不会产生错误,但librarymaterial_id 不会得到更新。
【问题讨论】:
-
请注意,
system有一个命名空间。你需要一个命名空间管理器 -
@ThomasWeller 感谢您的纠正。我删除了我的评论。
-
正如@ThomasWeller 指出的那样,您需要一个命名空间管理器来执行此操作,请仔细阅读此答案:stackoverflow.com/a/1089210/4222487
-
我正在设置它 - 谢谢