0

I need to fetch username and password values from sample XML tags

<CommCellUser userName="~!@#$%^&*()_+`1=- 23)()();';" password="":>?<,./;'|}{[]  ><:"/" </CommCellUser>

The value will be in double quotes. That value may contain double quotes and any other special characters including spaces .

comm_cell_line=`grep "CommCellUser" /filename | head -1`
userName=`echo "$comm_cell_line" | awk '{print $2}' | cut -d"\"" -f2`
passwd=`echo "$comm_cell_line" | awk '{print $3}' | cut -d"\"" -f2`

Fetching like this miss so many cases. Because it may contain spaces and special characters in value.

Please help .

4

2 回答 2

0

以下解决方案对传递给userNamepassword属性的字符串进行编码,以便认为 XML 字符串有效。

#!/bin/bash

XML="<CommCellUser userName='~!@#$%^&amp;*()_+``1=- 23)()();&#39;;' password='&quot;:&gt;?&lt;,./;&#39;|}{[]  &gt;&lt;:&quot;/'></CommCellUser>"

USER=`echo $XML | xmllint --xpath "string(/CommCellUser/@userName)" -`
PASS=`echo $XML | xmllint --xpath "string(/CommCellUser/@password)" -`

echo username=$USER
echo password=$PASS

产生以下输出:

username=~!@#$%^&*()_+1=- 23)()();';
password=":>?<,./;'|}{[] ><:"/

由于您正在解析数据,因此您可以假设传入的数据是有效的。xmllint 命令可用于强制执行此检查。

笔记:

于 2012-11-22T19:58:56.717 回答
0

我希望您示例中的密码值是错字。否则你的 xml 可能有问题。所以我从密码值中删除了双引号。看看下面的测试,grep 是你从文本中获取东西的朋友:

kent$  echo $comm_cell_line                                           
<CommCellUser userName="~!@#$%^&*()_+`1=- 23)()();';" password="quote removed:>?<,./;'|}{[]  ><:"/" </CommCellUser>

kent$  userName=$(grep -Po '(?<=userName=")[^"]*' <<<$comm_cell_line )

kent$  pwd=$(grep -Po '(?<=password=")[^"]*' <<<$comm_cell_line )     

kent$  echo $userName                                                 
~!@#$%^&*()_+`1=- 23)()();';

kent$  echo $pwd     
quote removed:>?<,./;'|}{[]  ><:
于 2012-11-22T22:28:43.030 回答