在 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 & call :cmErrorLevel %errorlevel% & 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')
但不起作用。
有人能解决我的问题吗?
最佳答案
刚刚看到这个是因为我正在寻找类似问题的解决方案。
我将您的 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 & call :cmErrorLevel %errorlevel% & 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
这就是您正在寻找的东西吗?如果您已经解决了,那么您使用了什么解决方案?
关于python字符串解析不解析换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22669980/