c# - Extract Xml Element from a larger string -


i have string starts xml element proceeds regular text after element has ended.

like so:

<someelement someatt="somevalue"><somechild/></someelement> more random text. 

i want parse first part xelement , separate out following text string variable. have considered counting anglebrackets, there legal xml throw me off. prefer use out-of-the-box parsers. have tried using xmlreader , xelement.parse method. them stop after element read instead of throwing exceptions because of unexpected text after xml element. haven't been able far. xmlreader has readsubtree method, couldn't work.

any ideas?

edit

  • additional info: random text may contain angle brackets.
  • additional info: conceptually, xml may contain xml comments, may contain non matching brackets. so, desirable solution account in order applicable, not necessary in specific case.

one possible simple approach maybe wrap entire string within root node make valid xml , parseable xelement or xdocument :

var xml = @"<someelement someatt=""somevalue""><somechild/></someelement> more random text."; xml = string.format("<root>{0}</root>", xml); var doc = xdocument.parse(xml); var element = doc.root.elements().first(); var trailingstring = doc.root.lastnode;  console.writeline(element.tostring()); console.writeline(); console.writeline(trailingstring.tostring()); 

console output:

<someelement someatt="somevalue">   <somechild /> </someelement>   more random text. 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -