[英]Python: how to generate a unique identifier for an XML document?
XSLT has a generate-id( xml-document ) function. XSLT 有一个 generate-id( xml-document ) 功能。 With it I can create a unique identifier for an XML document.有了它,我可以为 XML 文档创建唯一标识符。
In Python how would I generate a unique identifier for an XML document?在 Python 中,如何为 XML 文档生成唯一标识符?
Note: the unique identifier should be based on the content of the XML document, not the file name of the XML document.注意:唯一标识符应基于 XML 文档的内容,而不是 XML 文档的文件名。 For example, this XML document例如,这个 XML 文档
<root>
<comment>Hello, World</comment>
</root>
and this XML document和这个 XML 文档
<document>
<test>Blah, Blah</test>
</document>
must generate different identifiers, even if their file names are identical.必须生成不同的标识符,即使它们的文件名相同。
I have a graph of XML documents.我有一个 XML 文档图。 So I need some way to recognize, "Hey, I've already seen this XML document."所以我需要某种方式来识别,“嘿,我已经看过这个 XML 文档了。” I don't want to compare entire XML documents.我不想比较整个 XML 文档。 Instead, I want to compare UUIDs that correspond to the XML.相反,我想比较对应于 XML 的 UUID。
A colleague just sent me the answer:一位同事刚刚给我发了答案:
For mapping text to an ID, we've used MD5 as one hash digest.为了将文本映射到 ID,我们使用 MD5 作为一个哈希摘要。 Give the md5() function an XML document (string) and it will return a 32-character identifier.给 md5() 函数一个 XML 文档(字符串),它将返回一个 32 个字符的标识符。
More details:更多细节:
import sys
import stdio
from hashlib import md5
def digest_md5(obj):
if type(obj) is unicode:
obj = obj.encode('utf8')
return md5(obj).hexdigest()
s = sys.stdin.readline()
stdio.writeln(digest_md5(s))
Then I turned it into an exe file.然后我把它变成了一个exe文件。
Then from a DOS command prompt I typed this command:然后在 DOS 命令提示符下,我输入了这个命令:
type input.txt | genid
where input.txt is:其中 input.txt 是:
<Document>Hello, World</Document>
And I got this output:我得到了这个输出:
df6f8283335bf3f657a89733e3d36b84
Beautiful!美丽的!
import uuid
unique_id = uuid.uuid1()
You can also generate hexadecimal id or integer id by您还可以通过以下方式生成十六进制 id 或整数 id
uuid.uuid1().hex # For hexadecimal id
uuid.uuid1().int # For integer id
import uuid
#Create unique filename
uid = uuid.uuid1() # Generate UUID
uidstr = str(uid.int)[:21]
clientoneID = "8888"
OrderID = (clientoneID + uidstr)
#Save unique xmlfile
xmlf = open(OrderID, 'w')
xmlf.write(xmlfile)#Content of your XML file
xmlf.close
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.