2015-04-16 68 views
0

我想提取<P>標籤下的前兩個句子。如何從xml字符串中提取特定值?

例如(輸入字符串):

<P align=justify><STRONG>Pricings<BR></STRONG>It was another active week for names leaving the database. The week's prints consisted of two ILS, and sever ITS.</P> 

所需的輸出字符串:

It was another active week for names leaving the database. The week's prints consisted of two ILS, and sever ITS. 

目前,我的功能下面是拋出以下錯誤:

System.Xml.XmlException: 'justify' is an unexpected token. The expected token is '"' or ''

price = bottom.Substring(bottom.IndexOf("Pricings"), 8); 

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(bottom); 


XmlNodeList pList = doc.SelectNodes("/P[@align='justify']/strong"); 

foreach (XmlNode pValue in pList) 
{ 
    string innerText = pValue.ChildNodes[0].InnerText; 
    innerText = result; 
} 

我有點不清楚,怎麼去解決這個問題。感謝您的進一步幫助。

+0

你的HTML是不是一個有效的XML字符串。它不能使用XmlDocument加載。 – wonderbell

回答

2

它不是XML字符串,而是HTML。由於HTML本身通常可能不是格式良好的(在你的情況下它不是格式良好的),所以通常你不能使用XML解析器來解析HTML。

相反,您可以使用HTML Agility Pack(推薦的方式),或使用正則表達式解析此文本(通常不推薦,但有時可能)。

下面是示例代碼如何使用HtmlAgility包來獲得你幾乎資料:

var s = "<P align=justify><STRONG>Pricings<BR></STRONG>It was another active week for names leaving the database. The week's prints consisted of two ILS, and sever ITS.</P>"; 

var doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml(s); 

string result; 
var p = doc.DocumentNode.SelectSingleNode("p"); 
if (p.ChildNodes.Count == 2) 
    result = p.ChildNodes[1].InnerText; 

注:HTML敏捷包還可以作爲NuGet包在Visual Studio。

+0

非常感謝您的大力幫助。 – user3070072

1

我只是在做php/magento,試試這個來解決。

$xml = simplexml_load_file("../app/etc/local.xml") or die("X");$host = $xml->xpath('global/resources/default_setup/connection/host');$host = $host[0][0];$usernm = $xml->xpath('global/resources/default_setup/connection/username');$usernm = $usernm[0][0];$pwd = $xml->xpath('global/resources/default_setup/connection/password');$pwd = $pwd[0][0];$db = $xml->xpath('global/resources/default_setup/connection/dbname');$db = $db[0][0];$link = mysql_connect($host, $usernm, $pwd); 
If (!$link) { die ('Could not connect: ' . mysql_error()); } 
mysql_select_db($db) or die ('Unable to select database'); 

$result = mysql_query("SELECT * FROM catalog_product_flat_1 Where shipping_price IS NULL AND type_id='simple'"); 
$noOfRecord = mysql_num_rows($result); 

我使用XML文件作爲其位於Magento的/應用程序的/ etc/local.xml中Magento的local.xml文件,..

+0

你的回答看起來與問題完全無關。 OP的問題與你的答案中提到的php,magento,mysql和其他東西無關。你錯過了要回答的問題嗎? –