Python 字符串解析不解析换行符

1 投票
1 回答
1378 浏览
提问于 2025-04-18 00:02

在Python中,我想用minidom从XML标签中读取字符串。但是解析出来的字符串中的换行符却无法被识别。这里是我想解析的XML标签:

<Command>setlocal
C:\t\gfx\CMake2.8\bin\cmake.exe --check-stamp-file "C:\Source\Workspace\generate.stamp"
if %errorlevel% neq 0 goto :cmEnd
:cmEnd
endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone
:cmErrorLevel
exit /b %1
:cmDone
if %errorlevel% neq 0 goto :VCEnd</Command>

我的minidom解析代码是:

nodes = dom.getElementsByTagName("Command")
for j in range(len(nodes)):
  path = nodes[j].childNodes[0].nodeValue
  if path.find('\n') : 
    print '\n found'

但是这段代码没有效果,尽管字符串在“setlocal”、“:cmEnd”、“:cmErrorLevel”等结尾处有“\n”字符。我还尝试对输入字符串进行编码:

path = path.encode('utf-8')

然后运行上面的代码,但也没有效果。我还尝试了find('\\n'),但也不行。

有没有人能帮我解决这个问题?

1 个回答

1

我刚看到这个,正好在找类似问题的解决办法。

我把你的xml内容复制粘贴到一个文档里,然后把它保存成xml文件。

接着我做了这个

>>> xml = ('command.xml')
>>> xml_file = open(xml).read()
>>> xml_file 
'<Command>setlocal\nC:\\t\\gfx\\CMake2.8\\bin\\cmake.exe --check-stamp-file  "C:\\Source\\Workspace\\generate.stamp"\nif %errorlevel% neq 0 goto :cmEnd\n:cmEnd\nendlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone\n:cmErrorLevel\nexit /b %1\n:cmDone\nif %errorlevel% neq 0 goto :VCEnd</Command>'
>>> if '\n' in xml_file:
...     print '\\n found'
... 
\n found
>>> xml_file.count('\n')
8

这是不是你想要的那种?如果你已经解决了,那你用了什么办法呢?

撰写回答