簡體   English   中英

在 C# 中為 XML 文檔創建父節點

[英]Creating a Parent Node for XML document in C#

我的代碼:

// Read in Xml-file 
XmlDocument doc = new XmlDocument();
doc.Load("C:/Web.config");

XmlNode d = doc.SelectSingleNode("/configuration");
XmlNode MYNODE = doc.CreateNode("element", "connectionStrings", "");

//newParent.(childNode);
d.AppendChild(MYNODE);

//Saving the document
doc.Save("C:/Web.config");

我的 Web.config 中的 MyOutput:

<connectionStrings />

我真正想要的 output 在我的 Web.config 中:

<connectionStrings>

</connectionStrings>

我必須在我的代碼中進行哪些更改才能獲得正確的 output? 另外,如果我想讓我的標簽出現在另一個標簽的上方,我必須怎么做...說我的 --SharePoint-- 標簽。

問候艾蒂安

output 是正確的。 由於您在connectionStrings標記中沒有任何子元素,因此它呈現為空標記。

<connectionStrings /><connectionStrings></connectionStrings>的含義相同。

如果要在特定節點之前插入標簽,請使用InsertBefore方法:

XmlNode sharePoint = doc.SelectSingleNode("SharePoint");
XmlNode MYNODE = doc.CreateNode("element", "connectionStrings", "");

doc.InsertBefore(MYNODE, sharePoint);

<ConnectionStrings>看起來都一樣。 <connectionStrings /><connectionStrings></connectionStrings>.

您可以使用AppendChild()InsertBefore()InsertAfter()方法來 position 您的節點。

您也許可以在元素中添加一些空白文本?

MYNODE.InnerText = " ";

或者其他一些內容——也許是評論? 沒有一些內容,兩個 forms 幾乎相同。

重新提出“標簽”問題-這取決於您的意思...但是XmlNode具有InsertBeforeInsertAfter只需找到您希望它與之相鄰的節點並使用其中之一即可。

它們都是格式良好的 xml 格式。

但是,如果您向附加的子節點添加新的子節點,您將得到您想要的。 例如,只需在 connectionstrings 節點中添加一個空格:

XmlNode MYNODE = doc.CreateNode("element", "connectionStrings", "");
MYNODE.InnerText = " ";

這對連接字符串元素的實際使用沒有影響.. 但是 output 將如您所願。

抱歉來晚了,但我忍不住回復這個帖子:

XmlNode xNode = xDoc.CreateNode("element", "FundDetails", ""); // Parent node to insert
xDoc.InsertBefore(xNode, xDoc.ParentNode); // inserting parent node to existing XML document

此代碼幫助父節點從數據庫中獲取更多數據。

 XmlNode dataNode = doc.CreateNode(XmlNodeType.Element, "connectionstrings", null);
                 root.PrependChild(dataNode);
                for (int i = 1; i < root.ChildNodes.Count; i++)
                {
                    dataNode.AppendChild(root.ChildNodes[i]);
                    i--;
                }

如果您向附加的子節點添加新的子節點,您將得到您想要的。 例如,只需將 NULL 添加到連接字符串節點中。

XmlNode root = doc.DocumentElement;
root.InsertAfter(connNODE, root.FirstChild);

這是我需要做的,以便將我的節點放置在正確的位置。 感謝大家的幫助! 艾蒂安

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM