简体   繁体   English

想要使用c#将特定节点保存到Xml文件中

[英]Want to save particular node into the Xml File using c#

  1. code below: 代码如下:

     protected void generate_Click(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load("XmlFileName"); XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField"); if (node != null) { node.ChildNodes.Item(0).InnerXml = "hi"; doc.Save("XmlFileName"); } } 
  2. Showing null refernce here, 在这里显示null引用,

     node.ChildNodes.Item(0).InnerXml = "hi"; 
  3. Is the code is correct,the code behind running not showing any error but the Xaxisfield is not added. 代码是否正确,运行后的代码没有显示任何错误但是没有添加Xaxisfield。

     <?xml version="1.0" encoding="utf-8" ?> <ChartData> <XaxisFields> <XaxisField></XaxisField> </XaxisFields> </ChartData> 
  4. List item 项目清单

I want to add the childnode Xaxisfield in the xml file by selcting the particular parent node 我想通过选择特定的父节点在xml文件中添加childnode Xaxisfield

You can use Linq to Xml to select your node and update its value: 您可以使用Linq to Xml来选择节点并更新其值:

var xdoc = XDocument.Load("XmlFileName");
xdoc.Root.Element("XaxisFields").Element("XaxisField").Value = "hi";
// OR
// xdoc.XPathSelectElement("//XaxisField").Value = "hi";
xdoc.Save("XmlFileName");

Also your code is not working because there is no child nodes of XaxisField node. 此外,您的代码无法正常工作,因为XaxisField节点没有子节点。 This will work: 这将有效:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("XmlFileName");
XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField");
if (node != null)
{
    node.InnerXml = "hi";
    doc.Save("XmlFileName");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM