<?xml version="1.0" encoding="utf-8"?>
<Sequence>
<Inputs>
<Input>readOF</Input>
<Input>readReference</Input>
</Inputs>
</Steps>
</Sequence>
Мне нужно прокомментировать и раскомментировать четвертую строку этого файла XAML с использованием свойств System.XML: Желаемый результат:
<!--<Input>readOF</Input>-->
Это мой узел:
// Get the target node using XPath
System.Xml.XmlNode elementToComment = xDocument.SelectSingleNode("//Sequence/Inputs/Input");
Мой код работает только в том случае, если у меня есть только один ввод, я могу определить свой элемент без каких-либо проблем
но когда у меня есть несколько входных данных и вы пытаетесь добавить его значение в мой выбор узла, как это ничего не работает:
System.Xml.XmlNode elementToComment = xDocument.SelectSingleNode("//Sequence/Inputs/Input/ReadOF");
поэтому мой вопрос заключается в том, как добавить значение узла в код.
вот мой код:
// Find the proper path to the XML file
String xmlFilePath = "path\\xmfile.xml";
// Create an XmlDocument
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
// Load the XML file in to the document
xmlDocument.Load(xmlFilePath);
// Get the target node using XPath
System.Xml.XmlNode elementToComment = xmlDocument.SelectSingleNode("/Sequence/Inputs/Input");
// Get the XML content of the target node
String commentContents = elementToComment.OuterXml;
// Create a new comment node
// Its contents are the XML content of target node
System.Xml.XmlComment commentNode = xmlDocument.CreateComment(commentContents);
// Get a reference to the parent of the target node
System.Xml.XmlNode parentNode = elementToComment.ParentNode;
// Replace the target node with the comment
parentNode.ReplaceChild(commentNode, elementToComment);
xmlDocument.Save(xmlFilePath);
MessageBox.Show("ok");
Извините за мой английский, спасибо за внимание.
Одним из решений было бы выбрать родительский узел, перебрать его через дочерние элементы и заменить тот, который имеет InnerText == "readOF". Как это:
System.Xml.XmlNode inputs = xmlDocument.SelectSingleNode("/Sequence/Inputs");
foreach (System.Xml.XmlNode child in inputs.ChildNodes)
{
if (child.InnerText == "readOF")
{
String commentContents = child.OuterXml;
System.Xml.XmlComment commentNode = xmlDocument.CreateComment(commentContents);
inputs.RemoveChild(child);
inputs.PrependChild(commentNode);
break;
}
}
Использовать xml linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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);
XElement input = doc.Descendants("Input").Where(x => (string)x == "readOF").FirstOrDefault();
input.ReplaceWith("<!--<Input>readOF</Input>-->");
doc.Save(FILENAME);
}
}
}