我是C#编程和XML的新手。我想用日期(我将从日期选择器中选择)更改字符串(以@开头并以'开头),请查看下面的XML文件
<steps>
<step1>drop table emp1 purge</step1>
<step2>create table emp1 as select e1.first_name ,e1.last_name ,e1.phone_number ,e1.salary ,e1.hire_date from employees e1 where e1.hire_date between '@m_start_date' to '@m_end_date' group by e1.first_name ,e1.last_name ,e1.phone_number ,e1.salary ,e1.hire_date</step2>
<step3>select * from emp1</step3>
</steps>
在上面的Xml代码中,我想用'01 -sep-2012'更改@m_start_date,用'30 -sep-2012更改@m_end_date'最重要的一点是字符串@m_start_date和@m_end_date没有修复它我的更改其他xml文件(即它可能是@wk_start_dte和wk_end_dte)所以我需要一个C#中的逻辑,我们可以找到一个以@开头的字符串并以'结尾',所以我们可以用日期替换这个字符串。
预期结果应该是这样的
<steps>
<step1>drop table emp1 purge</step1>
<step2>create table emp1 as select e1.first_name ,e1.last_name ,e1.phone_number ,e1.salary ,e1.hire_date from employees e1 where e1.hire_date between '01-sep-2012' to '30-sep-2012' group by e1.first_name ,e1.last_name ,e1.phone_number ,e1.salary ,e1.hire_date</step2>
<step3>select * from emp1</step3>
</steps>
你能帮助我在C#中获得这个逻辑吗?
答案 0 :(得分:0)
假设您的XML位于名为test的字符串中:
test = System.Text.RegularExpressions
.Regex.Replace(test, "'[^']*start[^']*'", "'01-sep-2012'");
test = System.Text.RegularExpressions
.Regex.Replace(test, "'[^']*end[^']*'", "'30-sep-2012'");
答案 1 :(得分:0)
除了Ivan关于文本替换的答案之外,您可能需要执行以下操作才能找到节点
XmlDocument xDoc = new XmlDocument();
xDoc.Load("yourXml.XML");
XmlNode nodetoChange = xDoc.DocumentElement.SelectSingleNode("step2");
string xmlValue = nodetoChange.InnerText;
//Now apply Ivan's logic to replace text as you wish so that xmlValue new text
//then continue to save xml as shown below.
nodetoChange.InnterText = xmlValue;
xDoc.Save(); //In case you need to save it on hard-disk.
xDoc = null;
希望有所帮助, 谢谢 Milind