gpt4 book ai didi

c# - 如何使用 System.XAML 定义来自多个输入行的值来注释 C#/WPF 中的一行 XAML 文件

转载 作者:太空宇宙 更新时间:2023-11-03 12:09:56 24 4
gpt4 key购买 nike

<?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);

}


}


}

关于c# - 如何使用 System.XAML 定义来自多个输入行的值来注释 C#/WPF 中的一行 XAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52872399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com