<Demo_Test>
<Step ID="1">
<ACTION>Point</ACTION>
<CLASS_ID>dfsfsdf</CLASS_ID>
</Step>
<Step ID="2">
<ACTION>Point</ACTION>
<CLASS_ID>Avkddd</CLASS_ID>
</Step>
<Step ID="3">
<ACTION>Point</ACTION>
<CLASS_ID>afsasfa</CLASS_ID>
</Step>
<Step ID="4">
<ACTION>SubAction</ACTION>
<CLASS_ID>afsasfa</CLASS_ID>
</Step>
</Demo_Test>
我要修改具有“动作”节点值为“点”的“ CLASS_ID”的值 为此,我写了下面的代码,但不起作用
string l_xPath = "//Step/ACTION["Point"]";
XmlNodeList l_nodeList = l_doc.SelectNodes(l_xPath);
答案 0 :(得分:0)
我使用xml linq将结果放入字典中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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);
Dictionary<int, string> dict = doc.Descendants("Step")
.Where(x => (string)x.Element("ACTION") == "Point")
.GroupBy(x => (int)x.Attribute("ID"), y => (string)y.Element("CLASS_ID"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}
答案 1 :(得分:0)
您可以使用此:
var l_nodeList = l_doc.SelectNodes("//Step[ACTION='Point']");
foreach (XmlNode item in l_nodeList)
{
Console.WriteLine(item.SelectSingleNode("CLASS_ID").InnerText);
}
但是我更喜欢jdweng的答案
答案 2 :(得分:0)
首先,您需要一个像这样的对象:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="Step")]
public class Step {
[XmlElement(ElementName="ACTION")]
public string ACTION { get; set; }
[XmlElement(ElementName="CLASS_ID")]
public string CLASS_ID { get; set; }
[XmlAttribute(AttributeName="ID")]
public string ID { get; set; }
}
[XmlRoot(ElementName="Demo_Test")]
public class Demo_Test {
[XmlElement(ElementName="Step")]
public List<Step> Step { get; set; }
}
}
然后您可以使用以下方法对xml进行反序列化:
public static T XmlDeserializer<T>(string xmlString)
{
var instance = default(T);
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringreader = new StringReader(xmlString))
instance = (T)xmlSerializer.Deserialize(stringreader);
return instance;
}
然后像这样使用它:
var result = XmlDeserializer<Demo_Test >("your xml string here");
var l_nodeList =result.Step[0].CLASS_ID;
答案 3 :(得分:0)
此解决方案是使用XPath实现的
XmlDocument d = new XmlDocument();
d.Load(@"C:\Users\Desktop\test.xml");
XPathNavigator nav = d.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//Step[ACTION='Point']");
XPathNodeIterator iterator = nav.Select(exp);
var a = d.SelectNodes("//Step[ACTION='Point']");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.SelectSingleNode("CLASS_ID").Value);
}