[英]How to comment a line of a XAML file in C# /WPF with System.XAML defining value from multiple Inputs lines
<?xml version="1.0" encoding="utf-8"?>
<Sequence>
<Inputs>
<Input>readOF</Input>
<Input>readReference</Input>
</Inputs>
</Steps>
</Sequence>
我需要使用 System.XML 屬性注釋和取消注釋此 XAML 文件的第 4 行:所需輸出:
<!--<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");
對不起我的英語,感謝您的關注。
使用 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);
}
}
}
一種解決方案是選擇父節點,遍歷它的子節點,並替換具有 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.