POP Article V2.0 设为主页
收藏本站
首 页交流论坛留 言
您现在的位置:首 页 >> 热门开源项目 >> Berkeley DB >> 查看文章
Python读写Berlekey DB XML的例子
作者:MG个人技术博客  来源:www.sqlite.com.cn  时间:2008-2-8  【 字体: 】 〖 双击滚屏 〗

Python读写Berlekey DB XML的例子


  1. #!/usr/bin/env python
  2. # $Id: examples.py,v 1.23 2005/09/25 23:36:42 gmf Exp $
  3. # As of Python 2.3, there is a built-in module for Berkeley DB,
  4. # called bsddb.  The next uncommented line assumes that module is being used.
  5. # If you are using your own bsddb3 module, use this line:
  6. #      from bsddb3.db import *
  7. from bsddb3.db import *
  8. from dbxml import *
  9. book_content = r"<book><title>Knowledge Discovery in Databases.</title></book>"
  10. book_content_ns = r"<book xmlns:books='http://foo.bar.com/books.dtd'><books:title>Knowledge Discovery in Databases.</books:title></book>"
  11. book_name = r"book1"
  12. book_name_ns = r"book1_ns"
  13. def remove_database():
  14.     """Removes the databases so we can start with a fresh environment for
  15.     each test."""
  16.     import os, glob
  17.     databases = ["test", "test1", "test2"]
  18.     for database in databases:
  19.         files = glob.glob(database + "*.dbxml")
  20.         files += glob.glob("__db*")
  21.         files += glob.glob("log.*")
  22.         for file in files:
  23.             os.remove(file)
  24. def example01():
  25.     """Create an XmlManager/XmlContainer, add a document, get the document,
  26.     display the content of the document.
  27.     >>> remove_database()
  28.     >>> example01()
  29.     book1 = <book><title>Knowledge Discovery in Databases.</title></book>
  30.     """
  31.     mgr = XmlManager()
  32.     uc = mgr.createUpdateContext()
  33.     container = mgr.createContainer("./test.dbxml")
  34.     container.putDocument(book_name, book_content, uc)
  35.     document = container.getDocument(book_name)
  36.     s = document.getContent()
  37.     print document.getName(), "=", s
  38. def example02():
  39.     """Create an XmlManager/XmlContainer, add a document, query the container
  40.     for the document, iterate over the result set displaying the
  41.     values returned.
  42.     >>> remove_database()
  43.     >>> example02()
  44.     book1 = <book><title>Knowledge Discovery in Databases.</title></book>
  45.     """
  46.     mgr = XmlManager()
  47.     uc = mgr.createUpdateContext()
  48.     container = mgr.createContainer("test.dbxml")
  49.     container.putDocument(book_name, book_content, uc)
  50.     qc = mgr.createQueryContext()
  51.     results = mgr.query("collection('test.dbxml')/book", qc)
  52.     results.reset()
  53.     for value in results:
  54.         document = value.asDocument()
  55.         print document.getName(), "=", value.asString()
  56. def example03():
  57.     """Create an XmlContainer, add a document that includes a
  58.     namespace definition, create a query context, define a
  59.     namespace prefix to URI mapping, query the container
  60.     for the document within a context, iterate over the
  61.     result set displaying the values returned.
  62.     >>> remove_database()
  63.     >>> example03()
  64.     book1_ns = <book xmlns:books="http://foo.bar.com/books.dtd"><books:title>Knowledge Discovery in Databases.</books:title></book>
  65.     """
  66.     mgr = XmlManager()
  67.     uc = mgr.createUpdateContext()
  68.     container = mgr.createContainer("test.dbxml")
  69.     container.putDocument(book_name_ns, book_content_ns, uc)
  70.     qc = mgr.createQueryContext()
  71.     qc.setNamespace("books2", "http://foo.bar.com/books.dtd")
  72.     results = mgr.query("collection('test.dbxml')/*[books2:title='Knowledge Discovery in Databases.']", qc)
  73.     results.reset()
  74.     for value in results:
  75.         document = value.asDocument()
  76.         print document.getName(), "=", value.asString()
  77. def example04():
  78.     """Create an XmlContainer, define an equality string index
  79.     for booktitle elements, add a document, query the container
  80.     for the document, iterate over the result set displaying
  81.     the values returned.
  82.     Note that this example assumes that the 'test' container
  83.     does not already exist. If it does exist then the
  84.     addIndex method will throw an exception to complain
  85.     that the container isn't empty.
  86.     Python note: This exception is not passed on to Python, which
  87.     will abort the interpreter.
  88.     >>> remove_database()
  89.     >>> example04()
  90.     book1 = <book><title>Knowledge Discovery in Databases.</title></book>
  91.     """
  92.     mgr = XmlManager()
  93.     uc = mgr.createUpdateContext()
  94.     container = mgr.createContainer("test.dbxml")
  95.     container.addIndex("", "title", "node-element-equality-string", uc)
  96.     container.putDocument(book_name, book_content, uc)
  97.     qc = mgr.createQueryContext()
  98.     results = mgr.query("collection('test.dbxml')//*[title='Knowledge Discovery in Databases.']", qc)
  99.     for value in results:
  100.         document = value.asDocument()
  101.         print document.getName(), "=", value.asString()
  102. def example05():
  103.     """
  104.     Create an XmlContainer, define an equality string index
  105.     for booktitle elements, add a document, create a query
  106.     context, define a variable binding, query the container
  107.     for the document within a context referencing the variable
  108.     defined, iterate over the result set displaying the values
  109.     returned.
  110.     Note that this example assumes that the 'test' container
  111.     does not already exist. If it does exist then the
  112.     addIndex method will throw an exception to complain
  113.     that the container isn't empty.
  114.     Python note: This exception is not passed on to Python, which
  115.     will abort the interpreter.
  116.     >>> remove_database()
  117.     >>> example05()
  118.     book1 = <book><title>Knowledge Discovery in Databases.</title></book>
  119.     """
  120.     mgr = XmlManager()
  121.     uc = mgr.createUpdateContext()
  122.     container = mgr.createContainer("test.dbxml")
  123.     container.addIndex("", "title", "node-element-equality-string", uc)
  124.     container.putDocument(book_name, book_content, uc)
  125.     qc = mgr.createQueryContext()
  126.     results = mgr.query("collection('test.dbxml')//*[title='Knowledge Discovery in Databases.']", qc)
  127.     qc.setVariableValue("title", XmlValue("Knowledge Discovery in Databases."))
  128.     results = mgr.query("collection('test.dbxml')//*[title=$title]", qc)
  129.     for value in results:
  130.         document = value.asDocument()
  131.         print document.getName(), "=", value.asString()
  132. def example06():
  133.     """Create an XML Container, rename that container, delete the
  134.     container, and repeat.
  135.     >>> remove_database()
  136.     >>> example06()
  137.     """
  138.     mgr = XmlManager()
  139.     for i in range(2):
  140.     container = mgr.createContainer("test1.dbxml")
  141.     del container
  142.         mgr.renameContainer("test1.dbxml", "test2.dbxml")
  143.         container = mgr.openContainer("test2.dbxml")
  144.     del container
  145.         mgr.removeContainer("test2.dbxml")
  146. def example07():
  147.     """Create an use a transactional XML Container:
  148.     add a document, get the document, display the content of
  149.     the document.  Requires using DBEnv.
  150.     >>> remove_database()
  151.     >>> example07()
  152.     book1 = <book><title>Knowledge Discovery in Databases.</title></book>
  153.     """
  154.     environment = DBEnv()
  155.     environment.open(None, DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN, 0)
  156.     mgr = XmlManager(environment, 0)
  157.     uc = mgr.createUpdateContext()
  158.     container = mgr.createContainer("test.dbxml", DBXML_TRANSACTIONAL)
  159.     xtxn = mgr.createTransaction()
  160.     container.putDocument(xtxn, book_name, book_content, uc)
  161.     xtxn.commit()
  162.     document = container.getDocument(book_name)
  163.     s = document.getContent()
  164.     print document.getName(), "=", s
  165.     container.close()
  166.     mgr.removeContainer("test.dbxml")
  167.     environment.close(0)
  168. def example08():
  169.     """Create an XML Container within a Berkeley DB environment,
  170.     add a document, get the document, display the content of
  171.     the document.
  172.     >>> remove_database()
  173.     >>> example08()
  174.     book1 = <book><title>Knowledge Discovery in Databases.</title></book>
  175.     """
  176.     environment = DBEnv()
  177.     environment.open(None, DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN, 0)
  178.     mgr = XmlManager(environment, 0)
  179.     uc = mgr.createUpdateContext()
  180.     container = mgr.createContainer("test.dbxml")
  181.     container.putDocument(book_name, book_content, uc)
  182.     document = container.getDocument(book_name)
  183.     s = document.getContent()
  184.     print document.getName(), "=", s
  185.     container.close()
  186.     mgr.removeContainer("test.dbxml")
  187.     environment.close(0)
  188. def example09():
  189.     """Create an XML Container within a Berkeley DB environment,
  190.     then within a Berkeley DB transaction, add a document,
  191.     get the document, display the content of the document.
  192.     Use a Berkeley DB transaction
  193.     >>> remove_database()
  194.     >>> example09()
  195.     book1 = <book><title>Knowledge Discovery in Databases.</title></book>
  196.     """
  197.     environment = DBEnv()
  198.     environment.open(None, DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN, 0)
  199.     mgr = XmlManager(environment, 0)
  200.     uc = mgr.createUpdateContext()
  201.     container = mgr.createContainer("test.dbxml", DBXML_TRANSACTIONAL)
  202.     xtxn = mgr.createTransaction();
  203.     document = mgr.createDocument()
  204.     document.setContent(book_content)
  205.     document.setName(book_name)
  206.     container.putDocument(xtxn, document, uc)
  207.     document = container.getDocument(xtxn, book_name)
  208.     s = document.getContent()
  209.     print document.getName(), "=", s
  210.     xtxn.commit()
  211.     del document  # holds ref on container
  212.     del container # prevents removal
  213.     mgr.removeContainer("test.dbxml")
  214.     environment.close(0)
  215. def example10():
  216.     """ Create two XML Containers within a Berkeley DB environment,
  217.     then within a Berkeley DB transaction add a document to
  218.     each container.
  219.     >>> remove_database()
  220.     >>> example10()
  221.     """
  222.     environment = DBEnv()
  223.     environment.open(None, DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN, 0)
  224.     mgr = XmlManager(environment, 0)
  225.     uc = mgr.createUpdateContext()
  226.     txn = environment.txn_begin()
  227.     xtxn = mgr.createTransaction(txn)
  228.     container1 = mgr.createContainer(xtxn, "test.dbxml")
  229.     container2 = mgr.createContainer(xtxn, "test2.dbxml")
  230.     container1.putDocument(xtxn, book_name, book_content, uc)
  231.     container2.putDocument(xtxn, book_name, book_content, uc)
  232.     txn.commit(0)
  233.     del container1
  234.     del container2
  235.     del mgr
  236.     environment.close(0)
  237. def example11():
  238.     """Demonstrate the definition of an index, and the iteration over set set
  239.     of indexes specified
  240.     >>> remove_database()
  241.     >>> example11()
  242.     Indexes present:
  243.       http://www.sleepycat.com/2002/dbxml:name unique-node-metadata-equality-string
  244.       :title node-element-equality-date edge-element-equality-string
  245.     """
  246.     mgr = XmlManager()
  247.     container = mgr.createContainer("test.dbxml")
  248.     uc = mgr.createUpdateContext()
  249.     """ addIndex uri, name, indexType updateContext"""
  250.     # the following (commented) addIndex call is equivalent to the
  251.     # 2 that follow it.
  252.     #container.addIndex("", "title", "node-element-equality-date, edge-element-equality-string", uc)
  253.     container.addIndex("", "title", XmlIndexSpecification.NODE_ELEMENT|
  254.                XmlIndexSpecification.PATH_NODE|
  255.                XmlIndexSpecification.KEY_EQUALITY, XmlValue.DATE, uc)
  256.     container.addIndex("", "title", XmlIndexSpecification.NODE_ELEMENT|
  257.                XmlIndexSpecification.PATH_EDGE|
  258.                XmlIndexSpecification.KEY_EQUALITY, XmlValue.STRING, uc)
  259.     # this is another way to add indexes..
  260.     #    ispec = container.getIndexSpecification()
  261.     #    ispec.addIndex("", "title", XmlIndexSpecification.NODE_ELEMENT|
  262.     #        XmlIndexSpecification.PATH_NODE|XmlIndexSpecification.KEY_EQUALITY,
  263.     #        XmlValue.DATE);
  264.     #    container.setIndexSpecification(ispec, uc)
  265.     n = 0
  266.     print "Indexes present:"
  267.     for index in container.getIndexSpecification():
  268.       print "  %s:%s %s" % (index.get_uri(), index.get_name(), index.get_index())
  269.     container.putDocument("foo", "<title>1957-11-03</title>", uc)
  270.     qc = mgr.createQueryContext()
  271.     val = XmlValue(XmlValue.DATE, "1957-11-03")
  272.     res = container.lookupIndex(qc, "", "title", "node-element-equality-date",
  273.                 val)
  274.     # Shows how to look at a query plan
  275.     #print res.size()
  276.     #qe = mgr.prepare("collection('test.dbxml')/title[.<xs:date('1957-11-03')]", qc)
  277.     #print qe.getQueryPlan()
  278.    
  279. def example12():
  280.     """Use WholedocContainer by setting default container type on XmlManager
  281.     >>> remove_database()
  282.     >>> example12()
  283.     document:  <book><title text='\\"'>content's  got &quot; dquot</title></book>
  284.     """
  285.     content = r"<book><title text='\"'>content's  got &quot; dquot</title></book>"
  286.     mgr = XmlManager()
  287.     uc = mgr.createUpdateContext()
  288.     mgr.setDefaultContainerType(XmlContainer.WholedocContainer)
  289.     container = mgr.createContainer("test.dbxml")
  290.     container.putDocument(book_name, content, uc)
  291.     doc = container.getDocument(book_name)
  292.     print "document: ", doc.getContent()
  293. # Test example of an overloade XmlResolver instance in Python
  294. # Used in example 13
  295. class myResolver(XmlResolver):
  296.     def __init__(self):
  297.     XmlResolver.__init__(self)
  298.     print "XmlResolver constructor"
  299.     def resolveDocument(self, txn, mgr, uri, result):
  300.     print "In resolveDocument, uri: %s" % (uri)
  301.     content=r"<?xml version='1.0' ?><root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://xxx mysch.xsd'><a>yyz</a></root>"
  302.     doc = mgr.createDocument()
  303.     doc.setContent(content)
  304.     newval = XmlValue(doc)
  305.     result.setValue(result, newval)
  306.     return 1
  307.     def resolveCollection(self, txn, mgr, uri, result):
  308.     print "In resolveCollection, uri: %s" % (uri)
  309.     return 0
  310.     def resolveSchema(self, txn, mgr, location, nameSpace):
  311.     print "In resolveSchema, location: %s" % (location)
  312.     return 0
  313.     def resolveEntity(self, txn, mgr, systemId, publicId):
  314.     print "In resolveEntity, systemId: %s" % (systemId)
  315.     dtd =r"<?xml version='1.0' encoding='utf-8' ?><!ELEMENT root (a)><!ELEMENT a (#PCDATA)>"
  316.     dlen = len(dtd)
  317.     istr = mgr.createMemBufInputStream(dtd, dlen, "dtd")
  318.     return istr
  319.     def __del__(self):
  320.     XmlResolver.__del__(self)
  321. def example13():
  322.     """Example of creating an XmlResolver instance in Python
  323.     >>> remove_database()
  324.     >>> example13()
  325.     XmlResolver constructor
  326.     In resolveEntity, systemId: mydtd.dtd
  327.     In resolveDocument, uri: myscheme:/myscheme:xxx
  328.     value of result:  <a>yyz</a>
  329.     """
  330.    
  331.     resolver = myResolver()
  332.     mgr = XmlManager(DBXML_ALLOW_EXTERNAL_ACCESS)
  333.     mgr.registerResolver(resolver)
  334.     uc = mgr.createUpdateContext()
  335.     container = mgr.createContainer("test.dbxml", DBXML_ALLOW_VALIDATION,
  336.                     XmlContainer.NodeContainer)
  337.     container.putDocument("foo0", r"<?xml version='1.0' ?><!DOCTYPE root SYSTEM 'mydtd.dtd'><root><a>yyz</a></root>", uc);
  338.     container.putDocument("foo", "<root/>", uc);
  339.     container.putDocument(book_name, book_content, uc)
  340.     # query to test the resolver
  341.     qc = mgr.createQueryContext()
  342.     qc.setBaseURI("myscheme:/")
  343.     results = mgr.query("doc('myscheme:xxx')/root/a", qc)
  344.     for value in results:
  345.         document = value.asDocument()
  346.         print "value of result: ", value.asString()
  347. NUMBER_OF_EXAMPLES = 13
  348. def do_example(number):
  349.     print "Running example %d." % number
  350.     globals()["example%02d" % number]()
  351.    
  352. if __name__ == "__main__":
  353.     import sys
  354.     number = sys.argv[-1]
  355.     if number == "test":
  356.         import doctest, examples
  357.         doctest.testmod(examples)
  358.         sys.exit()
  359.        
  360.     try:
  361.         number = int(number)
  362.     except ValueError:
  363.         print "Usage: ./examples.py <example_number>|test"
  364.         sys.exit()
  365.     if number < 1 or number > NUMBER_OF_EXAMPLES:
  366.         print "Usage: ./examples.py <example_number>|test"
  367.         print "Example number out of range (1-%d)" % NUMBER_OF_EXAMPLES
  368.         sys.exit()
  369.     remove_database()
  370.     do_example(number)
浏览次数:   【 打 印 】【 关 闭
上一篇:已经没有了
下一篇:Berkeley DB XML and python
 论坛登陆
用户名:
密  码:
验证码: 
Cookie 选项:
正常登陆 隐身登陆
   
没有注册?
 文章搜索
 推荐文章
 酷站推荐
 热门文章
 网站统计
关于我们 | 网站地图 | 联系我们 | 网站历史 | 友情链接 | TOP
Copyright© 2006 Sqlite中文社区  程序开发: mistletoe  站长: 林轩 陈文成