<?xml version="1.0" encoding="utf-8"?>
<Sequence>
<Inputs>
<Input>readOF</Input>
<Input>readReference</Input>
</Inputs>
</Steps>
</Sequence>
我需要使用System.XML属性注释和取消注释该XAML文件的第四行: 所需的输出:
<!--<Input>readOF</Input>-->
这是我的节点:
// Get the target node using XPath
System.Xml.XmlNode elementToComment = xDocument.SelectSingleNode("//Sequence/Inputs/Input");
我的代码仅在只有一个输入巫婆的情况下才有效,我可以毫无问题地定义我的元素
但是当我有多个输入并试图将其值添加到我的Node选择中时,这种方法将无效:
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");
对不起,我的英语,谢谢您的关注。
答案 0 :(得分:1)
使用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);
}
}
}
答案 1 :(得分:0)
一种解决方案是选择父节点,遍历其子节点,然后替换具有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;
}
}