在其他文本中解析XML的最佳方法是什么

时间:2011-01-17 18:24:28

标签: c# xml parsing

如何在其他文本的中间解析xml。

示例:如果我在C#中有这个文本文件,我该如何解析xml部分:

-> Begin of file

2010-01-01 tehgvdhjjsad  
2010-01-02 dsjhnxcucncu  
14:55 iahsdahksdjh  

<Answer>
<headline>
<a1>1</a1>
<a2>2</a2>
</headline>
</Answer>
2010-01-05 tehgvddsda  
2010-01-05 ddsada  
22:55 iahsdahksdjh2  

<Answer>
<headline>
<a1>11</a1>
<a2>22</a2>
</headline>
</Answer>
-> End of file

2 个答案:

答案 0 :(得分:0)

有几种方法:

 1. Do a string.IndexOf("<Answer>") and then use a substring to chop off the header information.  Then add the substring like this:
xmlString = "<Answers>" + substringXml + "</Answers>".  Then you could parse the xml as valid XML.
 2. Use an xmltextreader created with fragment conformance levels and read through the xml.  Only stop on the Answer elements and do processing.
 3. Add a root element to the document and open it in an XmlDocument and use an xpath expression to read out the Answer elements.

答案 1 :(得分:0)

嗯,没有太多东西可以帮助你做些什么。 AFAIK有两种可能性:

选项1.如果所有xml片段具有相同的根节点,即。 “&lt; Answer&gt;”,然后您可以简单地找到&lt; Answer&gt;的出现次数。找到结束的下一个出现&lt; / Answer&gt;,在两者之间提取文本并使用普通的XML解析器。

选项2.如果它是一个任何东西xml有点事情,那么你可以使用我前段时间写的Regex based Html Parser。它应该没有问题地处理输入;但是,您必须处理打开/关闭元素并确定如何处理它们。

相关问题