[英]change xml value in c#
I am working on this since yesterday. 从昨天开始,我一直在为此工作。 I have an XML file which looks something like this
我有一个看起来像这样的XML文件
<catalog>
<captureInfo>
<row>5</row>
<col>5</col>
</captureInfo>
<patientInfo>
<name>XYZ</name>
<detail>details here</detail>
</patientInfo>
<imageData>
<r0c0>
<contrastFlag>true</contrastFlag>
</r0c0>
<r0c1>
<contrastFlag>true</contrastFlag>
</r0c1>
</imageData>
</catalog>
I need to update the value of contrastFlag
in the XML file. 我需要更新的价值
contrastFlag
XML文件英寸 This is the code I have written: 这是我编写的代码:
XmlDocument doc = new XmlDocument();
XmlNodeList imageData = doc.GetElementsByTagName("imageData");
foreach(XmlNode node in imageData)
{
foreach (XmlNode innernode in node)
{
if (innernode.Name == "r0c0")
{
innernode.InnerText = "false";
}
}
}
doc.Save("XMLFile1.xml");
Can anyone tell me where am I going wrong and also is there any better/faster approach for this? 谁能告诉我我要去哪里错,还有没有更好/更快的方法呢?
Well first off, your XML is malformed, the closing should match "catalog". 首先,您的XML格式不正确,结尾应匹配“目录”。 Why not just do this:
为什么不这样做:
string xml = @"<catalog>
<captureInfo>
<row>5</row>
<col>5</col>
</captureInfo>
<patientInfo>
<name>XYZ</name>
<detail>details here</detail>
</patientInfo>
<imageData>
<r0c0>
<contrastFlag>true</contrastFlag>
</r0c0>
<r0c1>
<contrastFlag>true</contrastFlag>
</r0c1>
</imageData>
</catalog>";
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
xdoc.SelectSingleNode("//catalog/imageData/r0c0/contrastFlag").InnerText = "false";
Here is a way to replace all of the instances using LINQ. 这是一种使用LINQ替换所有实例的方法。 I just wrote out to a new file to preserve the source.
我只是写了一个新文件来保留源代码。
StreamReader stream = new StreamReader(@"c:\test.xml");
XDocument doc = XDocument.Load(stream);
IEnumerable<XElement> flags = doc.Descendants("contrastFlag");
foreach (XElement e in flags)
{
e.Value = "false";
}
doc.Save(@"c:\test2.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.