Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

c# - There are multiple root elements load xml

sRecieved = "<XmlClient>2.0</XmlClient><XmlVersion>3.0</XmlVersion>" 
Dim xml As New XmlDocument();    
xml.LoadXml(sRecieved);

There are multiple root elements .....i want xmlclient value and xmlversion value

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well yes, your data isn't a valid XML document. (The error message is pretty clear - you've got multiple top-level elements.) You could make it a valid document by adding a dummy root element:

xml.LoadXml("<root>" & sReceived & "</root>")

... but if you get the chance to change whatever's sending the data, it would be better if it sent an actual XML document.

EDIT: If you're able to use LINQ to XML instead of XmlDocument, getting the client number and the version number are easy. For example, as text:

Dim clientVersion = doc.Root.Element("XmlClient").Value
Dim xmlVersion = doc.Root.Element("XmlVersion").Value 

EDIT: Okay, if you're stuck with XmlDocument, I believe you could use:

Dim clientVersionNode = doc.DocumentElement.GetElementsByTagName("XmlClient")(0)
Dim clientVersion = (CType(clientVersionNode, XmlElement)).InnerText

(and likewise for xmlVersion)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...