我正在尋找最簡單的方法將包含有效XML的字符串轉換爲C#中的XmlElement
對象。我需要將XML字符串轉換爲XmlElement
你怎麼能把它變成XmlElement
?
<item><name>wrench</name></item>
我正在尋找最簡單的方法將包含有效XML的字符串轉換爲C#中的XmlElement
對象。我需要將XML字符串轉換爲XmlElement
你怎麼能把它變成XmlElement
?
<item><name>wrench</name></item>
使用此:
private static XmlElement GetElement(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return doc.DocumentElement;
}
當心! 如果您需要首先將此元素添加到其他文檔,則需要使用ImportNode
導入它。
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
XmlElement root = doc.DocumentElement;
(或者如果你在談論的XElement,使用XDocument.Parse :)
XDocument doc = XDocument.Parse("<item><name>wrench</name></item>");
XElement root = doc.Root;
他想要這個元素,而對於XElement,他可以只做XElement.Parse(xmlString),但是你給他的文檔不是元素。 – 2010-09-13 18:13:07
@Jimmy Hoffa:如果你有一個文檔,直接獲取根元素,不是嗎? – dtb 2010-09-13 18:14:29
當然,只是說你的答案可以適合海報的問題多一點,以防他對我們來說不那麼容易.. – 2010-09-13 18:18:22
您可以使用XmlDocument.LoadXml()來執行此操作。
下面是一個簡單examle:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("YOUR XML STRING");
感謝您的回覆。 – Dean 2010-09-13 18:24:30
我想在這個片段中,得到了解決。
// Sample string in the XML format
String s = "<Result> No Records found !<Result/>";
// Create the instance of XmlDocument
XmlDocument doc = new XmlDocument();
// Loads the XML from the string
doc.LoadXml(s);
// Returns the XMLElement of the loaded XML String
XmlElement xe = doc.DocumentElement;
// Print the xe
Console.out.println("Result :" + xe);
如果還有其他更好的/有效的方法來實施,請告訴我們。
感謝&乾杯
假設你已經與孩子節點XmlDocument的,你需要從字符串添加更多的子元素。
XmlDocument xmlDoc = new XmlDocument();
// Add some child nodes manipulation in earlier
// ..
// Add more child nodes to existing XmlDocument from xml string
string strXml =
@"<item><name>wrench</name></item>
<item><name>screwdriver</name></item>";
XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
xmlDocFragment.InnerXml = strXml;
xmlDoc.SelectSingleNode("root").AppendChild(xmlDocFragment);
結果:
<root>
<item><name>this is earlier manipulation</name>
<item><name>wrench</name></item>
<item><name>screwdriver</name>
</root>
'XmlElement'或'XElement'? – SLaks 2010-09-13 18:08:28
字符串是否有單個根元素? – SLaks 2010-09-13 18:15:59
它不一定有根元素。 – Dean 2010-09-13 18:22:40