2012-06-10 47 views
-2

這是我的XML:添加文字F#中的XML節點

<location> 
    <hotspot name="name1" X="444" Y="518" /> 
    <hotspot name="name2" X="542" Y="452" /> 
    <hotspot name="name3" X="356" Y="15" /> 
</location> 

我想要做的是:

<location> 
    <hotspot name="name1" X="444" Y="518"> 
    <text> 
     This is the text I want to add in 
    </text> 
    </hotspot> 
    <hotspot name="name2" X="542" Y="452" /> 
    <hotspot name="name3" X="356" Y="15" /> 
</location> 

我不能添加文本,沒有問題新的節點。

+0

您正在遺漏很多信息。我們可以假設你在使用System.Xml嗎?你究竟試過了什麼? – ChaosPandion

回答

2

既然你XmlNode標籤的問題,我假設你正在使用從System.XmlXmlDocument類型(而不是更現代的LINQ to XML類型XDocument)。

要添加新節點的一些正文文本,你可以創建一個新元素(具有所需的名稱),然後設置其InnerText值屬性來指定在該節點的文本:

// Load XML document and find the parent node 
let doc = XmlDocument() 
doc.LoadXml("... your xml goes here ...") 
let parent = doc.SelectSingleNode("/location/hotspot[@name='name1']") 

// Create a new element and set its inner text 
let newNode = doc.CreateElement("text") 
newNode.InnerText <- "foo" 
parent.AppendChild(newNode) 

你可以當調用CreateElement時,也指定屬性來寫同樣的東西:

doc.CreateElement("text", InnerText = "foo") |> nd.AppendChild 
+0

這是正確的,但確實存在一種方法來讓「文本」元素不僅在一行上,而且正如我在第一篇文章中寫的那樣? –

+0

@FrankLioty是的。如果你想添加空格(比如新行和一些空格),那麼你可以使用'parent.AppendChild(doc.CreateWhitespace(「\ n」))''。 –

+0

我不能讓它工作:S –