2011-05-25 59 views
0

想在使用C#處理xml數據時請教一些建議。 我有一個小練習練習,我需要檢索特定標籤處的特定文本值。檢索xml文本值

我已經將元素節點的各種名稱分配給字符串值,並且用戶需要向控制檯輸入字符串值,並且如果名稱標記與輸入相同,則檢索定位在該標籤。 這是我使用的C#代碼,但我不知道如何檢索名稱標籤處的文本值。

int priceSpecific; 
     string destination; 
     ArrayList array = new ArrayList(); 
     xRootNode = xdoc.DocumentElement; 

     string firstValue = xRootNode.FirstChild.FirstChild.Name; 
     string secondValue = xRootNode.FirstChild.FirstChild.NextSibling.Name; 
     string thirdValue = xRootNode.FirstChild.FirstChild.NextSibling.NextSibling.Name; 
     string fourthValue = xRootNode.FirstChild.FirstChild.NextSibling.NextSibling.NextSibling.Name; 
     array.AddRange(new object[] { firstValue, secondValue, thirdValue, fourthValue}); 

     Console.WriteLine("Please enter your destination, first letter capital"); 
     destination = Console.ReadLine(); 

想法是循環arraylist並檢索與用戶的字符串輸入相同的元素節點的名稱。 有關如何檢索文本值的任何建議?

Regards

+0

你們是不是要選擇按名稱和它的值的節點? – varadarajan 2011-05-25 07:59:34

回答

1

這是一些非常討厭的代碼!我建議你花幾個小時學習Linq-to-XML。大致來說,如果要查找具有給定名稱的元素的值,可以按如下方式完成:

string elementName = "foo"; 
XDocument doc = XDocument.Parse("<xml document goes here>"); 
string matchedValue = doc.Descendants(elementName).Single().Value; 

更簡單!

+0

謝謝我知道,代碼是恐怖的。 – Arianule 2011-05-25 08:25:47

0

您可以使用多種方法,在方案中最有用似乎是:

  1. 的XmlDocument +的XPath(在所有的.NET版本支持)
  2. 的XmlReader(在所有.NET支持版本)
  3. 的XDocument(因爲.NET 3.0)
  4. 的XDocument無線與LINQ支持第LINQ語法

選擇3或4,優選如果.NET 3或以上可與XML文檔不是太大(幾個MB的文檔尺寸的邊界)。

選擇1使用XPath,這允許非常強的查詢到文檔結構


1.

XPathDocument document = new XPathDocument(@"myFile.xml"); 
XPathNavigator navigator = document.CreateNavigator(); 
string foundElementContent = 
    navigator.SelectSingleNode("//myElement[position()=1]/text()").ToString(); 

2.

string elementNameToFind = "myElement"; 
XmlReader xmlReader = XmlReader.Create(@"myFile.xml"); 
string foundElementContent = string.Empty; 
while (xmlReader.Read()) 
{ 
    if(xmlReader.NodeType==XmlNodeType.Element && 
     xmlReader.Name == elementNameToFind) 
    { 
    foundElementContent=xmlReader.ReadInnerXml(); 
    break; 
    } 
} 
xmlReader.Close(); 

3.

string elementNameToFind = "myElement"; 
XDocument xmlInMemoryDoc = XDocument.Load(@"myFile.xml"); 
XElement foundElement = xmlInMemoryDoc.Descendants(elementNameToFind).First(); 

4.

string elementNameToFind = "myElement"; 
XDocument xmlInMemoryDoc = XDocument.Load(@"myFile.xml"); 
XElement foundElement = 
    (
    from e in xmlInMemoryDoc.Descendants() 
    where e.Name == elementNameToFind 
    select e 
).First();