Вопрос

I'm trying to take in an xml file. The fields are always the same but sometimes not included.

How would I search for "Name" in vb ?

<product>
  <Name>
    <FirstName> John </FirstName>
    <LastName> Doe </LastName>
  </Name>
  <Age> 24 </Age>
  <DOB> 4/5/1990 </DOB>
</product> 

I tried the code below and got a compilation Error BC30456: 'Contains' is not a member of System.XML.Linq.XElement

dim doc as XDocument
if doc.Root.Element("product").Contains("Name") Then
   doc.Root.Element("product").Elements("Name").Remove()
end if  
Это было полезно?

Решение

The way to test if the element exists is to simply access it and then check if it is Nothing, like this:

If doc.Element("product").Element("Name") IsNot Nothing Then
    ' ...
End If

Notice that I used doc.Element("product") rather than doc.Root.Element("product") since, in your example XML, product is the root element. However, using the Element property like that is dangerous because it will throw an exception if the parent element doesn't exist. In other words, if doc.Element("product") returns Nothing, you can't then turn around and access Nothing.Element("Name"). So, to correct that, you'd have to do something like this:

If (doc.Element("product") IsNot Nothing) AndAlso (doc.Element("product").Element("Name") IsNot Nothing) Then
    ' ...
End If

But that get's ugly pretty fast. The easier way is to use the .<> syntax to access the elements, like this:

If doc.<product>.<Name>.FirstOrDefault IsNot Nothing Then
    ' ...
End If

That will return Nothing if either product or Name does not exist. It will not throw an exception if either or both of them were to be missing. If you did want it to throw an exception, you could still use the .<> syntax, but just call First rather than FirstOrDefault.

Of course, I could point out that all of this would be a bit easier, cleaner, and more flexible if you were to use XPath (the industry standard) rather than Microsoft's proprietary LINQ-to-XML technology, but that would just be petty. Ok, well, I guess it slipped out against my better judgement, so, as long as I've already said it, I might as well give an example:

If doc.XPathSelectElement("/product/Name") IsNot Nothing Then
    ' ...
End If
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top