We have a Java project which uses JSF. In our view layer we didn't use id
s in all our XHTML files. What I want to do is to parse XHTML files and check for tags like
我们有一个使用JSF的Java项目。在我们的视图层中,我们没有在所有XHTML文件中使用id。我想要做的是解析XHTML文件并检查标签
<h:inputText id="username" value="#{identity.username}"/>
The constant part is <h:input...
> The rest can be anything like <h:inputSecret
<h:inputWHATELSE
after selecting the correct tag. I want to check if there is an id
attribute of that tag. If not, I want to add an id
to it.
常量部分是
Here is one of our XHTML files.
这是我们的XHTML文件之一。
I tried to do the work with Python. I tried ElementTree, piksemel and BeautifulSoup. Any help about this issue will be appreciated.
我试着用Python做这个工作。我尝试过ElementTree,piksemel和BeautifulSoup。任何有关此问题的帮助将不胜感激。
1 个解决方案
#1
1
Using Beautifulsoup, you could do this as follows:
使用Beautifulsoup,你可以这样做:
from BeautifulSoup import BeautifulSoup
import re
soup = BeautifulSoup(<your_xml_here>)
nodes = soup.findAll(name=re.compile('^h:input'))
for node in nodes:
if 'id' not in dict(node.attrs):
node['id'] = <whatever you need>
As it can be seen, to get all the nodes that match the name pattern you're looking for all you need is a regular expression. After that, you can check the node attributes to make sure if id
is defined or not and assign a new value when needed.
可以看出,要获得所有与您正在寻找的名称模式匹配的节点,您需要的是一个正则表达式。之后,您可以检查节点属性以确定是否定义了id,并在需要时分配新值。
#1
1
Using Beautifulsoup, you could do this as follows:
使用Beautifulsoup,你可以这样做:
from BeautifulSoup import BeautifulSoup
import re
soup = BeautifulSoup(<your_xml_here>)
nodes = soup.findAll(name=re.compile('^h:input'))
for node in nodes:
if 'id' not in dict(node.attrs):
node['id'] = <whatever you need>
As it can be seen, to get all the nodes that match the name pattern you're looking for all you need is a regular expression. After that, you can check the node attributes to make sure if id
is defined or not and assign a new value when needed.
可以看出,要获得所有与您正在寻找的名称模式匹配的节点,您需要的是一个正则表达式。之后,您可以检查节点属性以确定是否定义了id,并在需要时分配新值。