2012-04-26 138 views
1

我的情況是這樣的,我有一個字符串格式的xml數據。從字符串中讀取數據XML

<?xml version="1.0" encoding="utf-16"?> 
<Tree AllowNodeEditing="True" ShowLineImages="False" CheckBoxes="True" EnableAjaxSkinRendering="False" AutoPostBackOnCheck="True" AutoPostBack="True"> 
<Node Text="IMG_1468.JPG" Value="../../CMS/Images/Fotogalerie/548/IMG_1468.JPG" Checked="True" Selected="True" tekst="Afbeelding IMG_1468.JPG" thumb="../../CMS/Images/Thumbs/548/IMG_1468.JPG" /> 

從上面的字符串我需要每個節點的選擇「值」並將其存儲在一個datatable.How我能實現這個..

+0

阿圖爾請張貼有點大碼等等我們可以理解你的字符串。 – 2012-04-26 10:42:42

回答

2

使用Linq to XML

XDocument doc = XDocument.Parse(xml_string); 
var values = (from f in doc.Elements().Descendants() 
       select f.Attribute("Value").Value).ToArray(); 
3

的一種方式是將字符串轉換爲xmlDoc中,比你可以閱讀xmlDoc中byusing LINQ:

字符串XML:

String rawXml = 
       @"<root> 
        <person firstname="Riley" lastname="Scott" /> 
        <person firstname="Thomas" lastname="Scott" /> 
       </root>"; 
     XmlDocument xmlDoc = new XmlDocument(); 
     xmlDoc.LoadXml(rawXml); 



var lv1s = from lv1 in xdoc.Descendants("person") 
      select new { 
       firstname = lv1.Attribute("firstname").Value, 
       lastname = lv1.Attribute("lastname").Value 
      }; 
+2

在.NET中可用於處理XML數據的許多選項中,XmlDocument遠不是最好的選擇。 – dtb 2012-04-26 10:44:46

+0

@dtb那麼你有什麼建議? – erikH 2012-04-26 10:46:58

+0

我建議[LINQ to XML](http://msdn.microsoft.com/en-us/library/bb387098.aspx),即[XDocument](http://msdn.microsoft.com/en-us /library/system.xml.linq.xdocument.aspx)。 – dtb 2012-04-26 10:52:15

1
XmlNodeList elementList = doc.GetElementsByTagName("*"); 
for (int i = 0; i < elementList.Count; i++) 
{ 
    string attrVal = elementList[i].Attributes["Value"].Value; 
} 
3

我會用XElement類。

XElement xmlTree = XElement.Parse("yourXMLString"); 

然後你就可以分析使用的XElement方法的每個元素,例如:

foreach (XElement el in xmlTree.Elements()) 
    // Do what you want with el 

你也可以查詢它:

<Tree> 
    <Node Text="IMG_1468.JPG" Value="../../CMS/Images/Fotogalerie/548/IMG_1468.JPG" /> 
</Tree> 

string yourValue = xmlTree.Elements("Node") 
         .Where(x => (string) x.Attribute("Text") == "IMG_1468.JPG") 
         .Select(x => (string) x.Attribute("Value")) 
         .Single(); 
1
XDocument doc = XDocument.Parse(xml); 
var values = from element in doc.XPathSelectElements("/Tree/Node") 
        where element.Attribute("Value") != null 
        select (element.Attribute("Value").Value);