2012-05-10 47 views
1

我有一個字符串,可能包含XML和普通字符串。我需要爲字符串中的所有實例解析出<math....</math>。我怎樣才能從這個字符串中解析出多個部分(從<math></math>)?什麼是乾淨的方式來解析C#中的字符串的多個部分?

Here is some content <math 
xmlns="http://www.w3.org/1998/Math/MathML"> 
<mi>a</mi><mo>&#x2260;</mo><mn>0</mn> </math>, that is mixed in with 
this other content <math xmlns="http://www.w3.org/1998/Math/MathML"> 
<mi>a</mi><msup><mi>x</mi><mn>2</mn></msup> <mo>+</mo> 
<mi>b</mi><mi>x</mi> <mo>+</mo> <mi>c</mi> <mo>=</mo> <mn>0</mn> 
</math> we want to be able to seperate this string 

背景: 我試圖使這個問題一般。我試圖做的具體是MVC3編碼與Raw。它會默認編碼所有內容。我不希望它編碼MathML,但確實希望它編碼一切。所以我想將其中的部分渲染爲Html.Raw(MathML部分),其餘部分我想通過正常編碼的字符串進行渲染。

+0

您是否能夠改變這個數據的格式?以「乾淨」的方式解析有點不一致的數據格式通常很困難。 –

+0

是的,這個數據的輸入是一個字符串。我想我可以轉換爲任何我需要更好地幫助解析它。 – Shane

+2

嗯,我的意思是字符串的格式。一個字符串很好,但是在大多數情況下將XML與非xml混合是一個壞主意(正如您發現的那樣)。如果它是兼容的XML,那麼你可以簡單地使用.NET的XML解析器。 –

回答

0

我不是正則表達式boffin,但這是我試過的,我得到了正確的結果。請用它作爲基礎,並在必要時進行修改。

我是從Stackoverflow的post得到的。

string yourstring = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"> <mi>a</mi><mo>&#x2260;</mo><mn>0</mn> </math>, that is mixed in with this other content <math xmlns=\"http://www.w3.org/1998/Math/MathML\"> <mi>a</mi><msup><mi>x</mi><mn>2</mn></msup> <mo>+</mo> <mi>b</mi><mi>x</mi> <mo>+</mo> <mi>c</mi> <mo>=</mo> <mn>0</mn> </math>"; 

try 
{ 
    yourstring = Regex.Replace(yourstring, "(<math[^>]+>.+?</math>)", ""); 
} 
catch (ArgumentException ex) 
{ 
    // Syntax error in the regular expression 
} 

結果字符串是:

, that is mixed in with this other content 
+0

可以工作。讓我玩這個,看看我能不能繼續下去。 – Shane

1

如果您通常希望XML格式良好或至少格式一致,則應該能夠使用regular expressions去除XML。

你可以用Expresso來試驗你的表情。

如果您想要解析您剝離的XML,這是.NET XMLParser的工作。

相關問題