Why i get text value from XML node what not have this text? And how get empty string?

61 Views Asked by At

My XML ↓.

<partsmanagement>
  <t1>thisText1</t1>
  <t2>thisText2</t2>
  <t3></t3>
  <part>
    text0
    <t1>thisText3</t1>
    <t2>thisText4</t2>
  </part>
</partsmanagement>

I use MSXML2 in VBA. Parent node return his text and all children text too. But i need only his text value. How can i get this?

This some example of results:

? xml.selectNodes("/partsmanagement").item(0).text
return this ↓
thisText1 thisText2
text0
thisText3 thisText4
' why it return not empty string? and how get empty string?

? xml.selectNodes("/partsmanagement/t1").item(0).text
return this ↓
thisText1 ' good

? xml.selectNodes("/partsmanagement/t2").item(0).text
return this ↓
thisText2 ' good

? xml.selectNodes("/partsmanagement/t3").item(0).text
return this ↓
  ' empty string, good 

? xml.selectNodes("/partsmanagement/part").item(0).text
return this ↓
text0 ' good
thisText1 thisText2 ' why it return this part? and how get only first row?

? xml.selectNodes("/partsmanagement/part/t1").item(0).text
return this ↓
thisText3

? xml.selectNodes("/partsmanagement/part/t2").item(0).text
return this ↓
thisText4

i want get this result:

? xml.selectNodes("/partsmanagement").item(0).text ->  ' empty string
? xml.selectNodes("/partsmanagement/part").item(0).text -> text0

How can i get this?

3

There are 3 best solutions below

0
taller On
? XML.SelectNodes("/partsmanagement/part").item(0).childNodes.item(0).text

OR 

? XML.SelectNodes("/partsmanagement/part").item(0).firstChild.text
text0
? XML.SelectNodes("/partsmanagement").item(0).childNodes.item(2).text
<empty string>
0
JSmart523 On

I think what you're looking for is

? xml.selectNodes(
  "/partsmanagement/*[0]/text()"
).text

Breaking down this XPath string:

  1. / - root node
  2. partsmanagement - all direct child elements named "partsmanagement"
  3. /* - all direct child elements (but not text nodes)
  4. [0] - Only the first of the direct child element (per partsmanagement element because it's applied per set of child elements)
  5. /text() - all direct child text nodes.
0
user23025019 On

Answer @JSmart523 brought me to the desired thought. I used other filter.

xml.SelectNodes("//node()") ' Matches any node of any kind

It allowed me to receive separately IXMLDOMText and IXMLDOMElement.