Locating the node by value containing whitespaces

2019-01-09 04:37发布

I need to locate the node within an xml file by its value using XPath. The problem araises when the node to find contains value with whitespaces inside. F.e.:

<Root>
  <Child>value</Child>
  <Child>value with spaces</Child>
</Root>

I can not construct the XPath locating the second Child node.

Simple XPath /Root/Child perfectly works for both children, but /Root[Child=value with spaces] returns an empty collection.

I have already tried masking spaces with %20, & #20;, & nbsp; and using quotes and double quotes.

Still no luck.

Does anybody have an idea?

7条回答
混吃等死
2楼-- · 2019-01-09 04:44

All of the above solutions didn't really work for me. However, there's a much simpler solution.

When you create the XMLDocument, make sure you set PreserveWhiteSpace property to true;

        XmlDocument xmldoc = new XmlDocument();
        xmldoc.PreserveWhitespace = true;
        xmldoc.Load(xmlCollection);
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-09 04:50

did you try #x20 ?

查看更多
beautiful°
4楼-- · 2019-01-09 04:50

i've googled this up like on the second link:

try to replace the space using "x0020"

this seems to work for the guy.

查看更多
神经病院院长
5楼-- · 2019-01-09 04:57

"x0020" worked for me on a jackrabbit based CQ5/AEM repository in which the property names had spaces. Below would work for a property "Record ID"-

[(jcr:contains(jcr:content/@Record_x0020_ID, 'test'))]
查看更多
Summer. ? 凉城
6楼-- · 2019-01-09 05:00

Locating the Attribute by value containing whitespaces using XPath

I have a input type element with value containing white space.

eg:

<input type="button"  value="Import&nbsp;Selected&nbsp;File">

I solved this by using this xpath expression.

//input[contains(@value,'Import') and contains(@value ,'Selected')and contains(@value ,'File')]

Hope this will help you guys.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-09 05:02

Try either this:

/Root/Child[normalize-space(text())=value without spaces]

or

/Root/Child[contains(text(),value without spaces)]

or (since it looks like your test value may be the issue)

/Root/Child[normalize-space(text())=normalize-space(value with spaces)]

Haven't actually executed any of these so the syntax may be wonky.

查看更多
登录 后发表回答