gpt4 book ai didi

c# - 无法在xml中的指定位置插入节点

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:27 25 4
gpt4 key购买 nike

我正在从 C# 代码创建 xml。我遇到了以下错误: 无法在指定位置插入节点。

我的代码是:

  try {           
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(docNode);

// XmlNode openerpNode = doc.CreateElement("open");
doc.AppendChild(openerpNode);

XmlElement dataNode = doc.CreateElement("dataex");
openerpNode.AppendChild(dataNode);
doc.PrependChild(colName.GenerateColumnsForTable("code", doc, dataNode)); //THIS LINE CAUSES ERROR AND THIS FUNCTON RETURNS A XmlNode TYPE OBJECT "dataNode"
//I use PrependChild here because i will call this function again passing another string in first parameter and it should attach the same xml
Console.WriteLine("string is : " + doc);
Console.ReadKey();
doc.Save("C:/cod.xml");
return true;
} catch (Exception ex) {
Console.WriteLine("The error is :" + ex);
Console.ReadKey();
return false;
}



public class ReturnColumnName
{
public XmlNode GenerateColumnsForTable(string tableName, XmlDocument doc, XmlNode dataNode)
{

//Here i am using the same doc and dataNode to create xml
return dataNode;
}
}

编辑:我从这里更改了代码

 doc.PrependChild(colName.GenerateColumnsForTable("code_pays_iso", doc, dataNode));   

 XmlNode nod = colName.GenerateColumnsForTable("code_colisage", doc,dataNode);
doc.AppendChild(doc.OwnerDocument.ImportNode(nod, true));

现在它给出了这个错误:

The error is :System.NullReferenceException: Object reference not set to an instance of an object.

谁能帮我找出错误的原因

最佳答案

你不能给自己添加一个节点

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

try
{
ReturnColumnName colName = new ReturnColumnName();
string input = "<?xml version=\"1.0\"?><open></open>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(input);
XmlElement opener = (XmlElement)doc.GetElementsByTagName("open")[0];

XmlElement dataNode = doc.CreateElement("dataex");

XmlElement child = (XmlElement)colName.GenerateColumnsForTable("code", doc, dataNode);
if (opener.ChildNodes.Count == 0)
{
opener.AppendChild(child);
}
else
{
opener.PrependChild(child);
}
}
catch (Exception ex)
{
Console.WriteLine("The error is :" + ex);
Console.ReadKey();
}

}
public class ReturnColumnName
{
public XmlNode GenerateColumnsForTable(string tableName, XmlDocument doc, XmlNode dataNode)
{

//Here i am using the same doc and dataNode to create xml
return dataNode;
}
}
}
}

关于c# - 无法在xml中的指定位置插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32330610/

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