2011-03-04 49 views
0

我有一个来自数据库的string。我想读这个为XML。字符串看起来像下面在.NET 2.0中以XML格式读取字符串

<settings> 
    <setting name="OfferIDs" value="47,48,49,50,51,52,53,76,77,78,79" /> 
    <setting name="someothersetting" value="" /> 
    <setting name="anothersetting" value="" /> 
</settings> 

我想获得的OfferIDs值作为使用VB.NET的字符串。提前谢谢了。

回答

2

没有访问LINQ,你的代码应该是这样的......

Dim xmlDoc As New System.Xml.XmlDocument 
xmlDoc.Load("YourXmlFile.xml") 
Dim OfferIDs As String = xmlDoc.SelectSingleNode("//settings/setting[@name='OfferIDs']").Attributes("value").Value 

这应该给你你在找什么。

5

编辑:要使用.NET 2,我可能会使用XmlDocument

Dim document = new XmlDocument() 
document.LoadXml(xml) 

那么你需要通过其name属性寻找合适的元素的文档浏览,然后采取value该元素的属性。我在XmlDocument这些天生疏,但我希望这足够让你开始...


最简单的方法是可能与LINQ加载它以XML:

Dim settings = XElement.Parse(xml) 

...然后查询它。在C#中很容易,但是我的VB-fu使LINQ查询部分失败。

C#的会是这样的:

XElement settings = XElement.Parse(xml); 
string offerIds = settings.Elements("setting") 
          .Where(x => (string) x.Attribute("name") == "OfferIDS") 
          .Select(x => (string) x.Attribute("value")) 
          .Single(); 
+1

的解决方案是在.NET 2.0,但答复 – Chin 2011-03-04 17:26:43

+0

@Chin千恩万谢遗憾的是不能使用LINQ:在未来,这将是值得在提问中提到这一点。我倾向于假定至少.NET 3.5这些天,考虑多久它已经出来。编辑... – 2011-03-04 17:27:59

+0

对不起,将来会做。 – Chin 2011-03-04 17:29:50

0

您可以使用StringReader结合XmlReader(快速,非缓存,只向前访问XML数据)从字符串中读取xml。 在C#:

string source = GetXmlAsString(); 
using (StringReader xml = new StringReader (source)) { 
    using (XmlReader reader = XmlReader.Create (xml)) { 
     while (reader.Read()) { 
      if (reader.IsStartElement ("setting")) { 
       string attrName = reader.GetAttribute ("name"); 
       if (attrName == "OfferIDs") { 
        string attrValue = reader.GetAttribute ("value"); 
       } 
      } 
     } 
    } 
} 

在VB:

Dim source As String = GetXmlAsString() 
Using xml As New StringReader(source) 
    Using reader As XmlReader = XmlReader.Create(xml) 
     While reader.Read() 
      If reader.IsStartElement("setting") Then 
       Dim attrName As String = reader.GetAttribute("name") 
       If attrName = "OfferIDs" Then 
        Dim attrValue As String = reader.GetAttribute("value") 
       End If 
      End If 
     End While 
    End Using 
End Using