我想從XML文檔中的特定元素獲取innertertext,通過一個字符串傳入,我不知道爲什麼它沒有找到任何節點。問題分析在c#中的XML文檔
此代碼運行良好,但從未進入FOREACH循環,因爲ocNodesCompany和ocNodesOrgs都具有xero元素。爲什麼GetElementsByTagName
找不到節點?
順便說一句我也試過:
XmlNodeList ocNodesOrgs = thisXmlDoc.SelectNodes("//OpenCalaisSimple/CalaisSimpleOutputFormat/Company")
代碼:
public static ArrayList getTwitterHandles(String ocXML)
{
ArrayList thisList = new ArrayList();
XmlDocument thisXmlDoc = new XmlDocument();
thisXmlDoc.LoadXml(ocXML);
//get Companies
XmlNodeList ocNodesCompany = thisXmlDoc.GetElementsByTagName("Company");
foreach (XmlElement element in ocNodesCompany)
{
thisList.Add(element.InnerText);
}
//Get Organisations
XmlNodeList ocNodesOrgs = thisXmlDoc.GetElementsByTagName("Organization");
foreach (XmlElement element in ocNodesOrgs)
{
thisList.Add(element.InnerText);
}
//Get Organisations
return thisList;
}
我的XML字符串是:
<!--Use of the Calais Web Service is governed by the Terms of Service located at http://www.opencalais.com. By using this service or the results of the service you agree to these terms of service.--><!-- Company: BBC,T-mobile,Vodafone,GE, IndustryTerm: open calais services, Organization: Federal Bureau of Investigation,Red Cross,Greenpeace,Royal Navy,-->
<OpenCalaisSimple>
<Description>
<calaisRequestID>38cb8898-48ba-85ff-12e9-f8d629568428</calaisRequestID>
<id>http://id.opencalais.com/lt0Hf8XWIr2DNIJzNlaXlA</id>
<about>http://d.opencalais.com/dochash-1/ff929eb2-de43-3ed1-8ee4-6109abf6bf77</about>
<docTitle/>
<docDate>2011-03-10 06:36:08.646</docDate>
<externalMetadata/>
</Description>
<CalaisSimpleOutputFormat>
<Company count="1" relevance="0.603" normalized="British Broadcasting Corporation">BBC</Company>
<Company count="1" relevance="0.603" normalized="T-MOBILE NETHERLANDS HOLDING B.V.">T-mobile</Company>
<Company count="1" relevance="0.603" normalized="Vodafone Group Plc">Vodafone</Company>
<Company count="1" relevance="0.603" normalized="General Electric Company">GE</Company>
<IndustryTerm count="1" relevance="0.603">open calais services</IndustryTerm>
<Organization count="1" relevance="0.603">Red Cross</Organization>
<Organization count="1" relevance="0.603">Greenpeace</Organization>
<Organization count="1" relevance="0.603">Royal Navy</Organization>
<Topics>
<Topic Taxonomy="Calais" Score="0.899">Human Interest</Topic>
<Topic Taxonomy="Calais" Score="0.694">Technology_Internet</Topic>
</Topics>
</CalaisSimpleOutputFormat>
</OpenCalaisSimple>
看起來像你應該使用XPath查詢來獲取你想要接收的元素。你可以閱讀一下[這裏] [1] [1]:http://msdn.microsoft.com/en-us/library/bb156083.aspx – madcyree 2011-03-11 09:25:34
這可能是一個愚蠢的問題,但有您調查了XML Document對象的InnerXml以驗證它作爲參數傳遞時是否正確加載? – FarligOpptreden 2011-03-11 09:32:14
我測試了這個,代碼似乎正常工作。檢查您在ocXML參數中是否有正確的數據,並確認它已正確加載。 – mgronber 2011-03-11 09:41:39