невозможно добавить строку в базу данных: BaseXException: имя недопустимо

После добавления действительного XML из файла в BaseX, как мне теперь добавить действительное XML из String?

thufir@dur:~/NetBeansProjects/twitterBaseX$ 
thufir@dur:~/NetBeansProjects/twitterBaseX$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> list
Name                 Resources  Size    Input Path                               
-------------------------------------------------------------------------------
com.w3schools.books  1          6290    https://www.w3schools.com/xml/books.xml  
db                   1          101838                                           
twitter              0          4570                                             
w3school_data        1          5209    https://www.w3schools.com/xml/note.xml   

4 database(s).
> 
> drop database twitter
Database 'twitter' was dropped.
> 
> exit
Have fun.
thufir@dur:~/NetBeansProjects/twitterBaseX$ 
thufir@dur:~/NetBeansProjects/twitterBaseX$ gradle clean run

> Task :run FAILED                                                                              
/home/thufir/basex/.basex: writing new configuration file.
Feb. 03, 2020 2:23:10 A.M. basex.DatabaseHelper add
INFO: <?xml version="1.0" encoding="UTF-8"?><root><metadata><result_type>recent</result_type><iso_language_code>und</iso_language_code></metadata><in_reply_to_status_id_str>1223800963196162049</in_reply_to_status_id_str><in_reply_to_status_id>1223800963196162049</in_reply_to_status_id><created_at>Mon Feb 03 07:50:03 +0000 2020</created_at><in_reply_to_user_id_str>60919433</in_reply_to_user_id_str><source>&lt;a href=&quot;http://twitter.com/download/iphone&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPhone&lt;/a&gt;</source><retweet_count>0</retweet_count><retweeted>false</retweeted><geo>null</geo><in_reply_to_screen_name>lizardbill</in_reply_to_screen_name><is_quote_status>false</is_quote_status><id_str>1224238604437733378</id_str><in_reply_to_user_id>60919433</in_reply_to_user_id><favorite_count>0</favorite_count><id>1224238604437733378</id><text>@lizardbill ???????? excised url</text><place>null</place><lang>und</lang><favorited>false</favorited><possibly_sensitive>false</possibly_sensitive><coordinates>null</coordinates><truncated>false</truncated><entities><urls><display_url>shop.yang2020.com</display_url><indices>15</indices><indices>38</indices><expanded_url>http://shop.yang2020.com</expanded_url><url>excised</url></urls><user_mentions><indices>0</indices><indices>11</indices><screen_name>lizardbill</screen_name><id_str>60919433</id_str><name>Bill the Lizard</name><id>60919433</id></user_mentions></entities><contributors>null</contributors><user><utc_offset>null</utc_offset><friends_count>197</friends_count><profile_image_url_https>https://pbs.twimg.com/profile_images/1208330461518237696/GOo2AZX1_normal.jpg</profile_image_url_https><listed_count>1</listed_count><profile_background_image_url>null</profile_background_image_url><default_profile_image>false</default_profile_image><favourites_count>11211</favourites_count><description>WE NEED ALL HANDS ON DECK! #YangGang Quick-Start Guide: excised + @IowaforYang @TeamYangNH @SCforYang @NevadaforYang ????</description><created_at>Wed Jul 17 04:44:43 +0000 2019</created_at><is_translator>false</is_translator><profile_background_image_url_https>null</profile_background_image_url_https><protected>false</protected><screen_name>humansforyang</screen_name><id_str>1151352001579511808</id_str><profile_link_color>1DA1F2</profile_link_color><is_translation_enabled>false</is_translation_enabled><translator_type>none</translator_type><id>1151352001579511808</id><geo_enabled>false</geo_enabled><profile_background_color>F5F8FA</profile_background_color><lang>null</lang><has_extended_profile>false</has_extended_profile><profile_sidebar_border_color>C0DEED</profile_sidebar_border_color><profile_text_color>333333</profile_text_color><verified>false</verified><profile_image_url>http://pbs.twimg.com/profile_images/1208330461518237696/GOo2AZX1_normal.jpg</profile_image_url><time_zone>null</time_zone><url>excisted</url><contributors_enabled>false</contributors_enabled><profile_background_tile>false</profile_background_tile><profile_banner_url>https://pbs.twimg.com/profile_banners/1151352001579511808/1576927762</profile_banner_url><entities><description><urls><display_url>bit.ly/welcome_to_the…</display_url><indices>56</indices><indices>79</indices><expanded_url>excised  </expanded_url><url>edited</url></urls></description><url><urls><display_url>yang2020.com/what-is-freedo…</display_url><indices>0</indices><indices>23</indices><expanded_url>https://www.yang2020.com/what-is-freedom-dividend-faq/</expanded_url><url>excised</url></urls></url></entities><statuses_count>4503</statuses_count><follow_request_sent>false</follow_request_sent><followers_count>410</followers_count><profile_use_background_image>true</profile_use_background_image><default_profile>true</default_profile><following>false</following><name>Humans for Yang ????</name><location>UBI FAQ ????</location><profile_sidebar_fill_color>DDEEF6</profile_sidebar_fill_color><notifications>false</notifications></user></root>
Exception in thread "main" org.basex.core.BaseXException: Name '' is invalid.
        at org.basex.core.Command.execute(Command.java:94)
        at org.basex.core.Command.execute(Command.java:116)
        at basex.DatabaseHelper.add(DatabaseHelper.java:83)
        at basex.DatabaseHelper.dropCreateAdd(DatabaseHelper.java:91)
        at main.App.twitterToBaseX(App.java:24)
        at main.App.main(App.java:28)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':run'.
> Process 'command '/home/thufir/.sdkman/candidates/java/12.0.1-zulu/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
4 actionable tasks: 4 executed
thufir@dur:~/NetBeansProjects/twitterBaseX$                                                     
thufir@dur:~/NetBeansProjects/twitterBaseX$                                                     

конструктор для добавления:

Add

public Add(java.lang.String path,
   java.lang.String input)

Constructor, specifying a target path and an input.

Parameters:
    path - target path, optionally terminated by a new file name. If null, the name of the input will be set as path.
    input - input file or XML string

код:

package basex;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.logging.Logger;
import org.basex.core.BaseXException;
import org.basex.core.Context;
import org.basex.core.cmd.Add;
import org.basex.core.cmd.Open;
import org.basex.core.cmd.CreateDB;
import org.basex.core.cmd.DropDB;
import org.basex.core.cmd.List;
import org.basex.core.cmd.Set;
import org.json.XML;
import twitter4j.JSONArray;
import twitter4j.JSONException;

public class DatabaseHelper {

    private static final Logger log = Logger.getLogger(DatabaseHelper.class.getName());
    private Properties properties = new Properties();
    private URL url = null;
    private String databaseName = null;
    private Context context = null;
    private String parserType = null;

    private DatabaseHelper() {
    }

    public DatabaseHelper(Properties properties) {
        this.properties = properties;
    }

    private String wrap(String string) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        stringBuilder.append("<root>");
        stringBuilder.append(string);
        stringBuilder.append("</root>");
        return stringBuilder.toString();
    }

    private void init() throws MalformedURLException, BaseXException {
        log.fine(properties.toString());
        parserType = properties.getProperty("parserType");
        url = new URL(properties.getProperty(parserType + "URL"));
        databaseName = properties.getProperty("databaseName");
        context = new Context();
        list();
    }

    private void list() throws BaseXException {
        log.fine(new List().execute(context));
    }

    private void drop() throws BaseXException {
        new Set("parser", parserType).execute(context);
        new DropDB(databaseName).execute(context);
        list();
    }

    private void create() throws BaseXException, JSONException {
        new Set("parser", parserType).execute(context);
        new CreateDB(databaseName).execute(context);
        new List().execute(context);
        list();
    }

    private void add(JSONArray tweets) throws JSONException, BaseXException {
        long id = 0L;
        String jsonStringTweet = null;
        org.json.JSONObject jsonObjectTweet = null;
        String stringXml = null;

        new Open(databaseName).execute(context);
        for (int i = 0; i < tweets.length(); i++) {
            jsonStringTweet = tweets.get(i).toString();
            jsonObjectTweet = new org.json.JSONObject(jsonStringTweet);
            stringXml = XML.toString(jsonObjectTweet);
            stringXml = wrap(stringXml);
            log.info(stringXml);
            new Add(null, stringXml).execute(context);
        }
    }

    public void dropCreateAdd(JSONArray tweets) throws MalformedURLException, BaseXException, JSONException {
        init();
        drop();
        create();
        add(tweets);
        list();
    }

}

Я добавил метод wrap, чтобы полученный String прошел проверку как:

XML-документ действителен.

При этом я даже не уверен, на какое «Имя» ссылается ошибка. База данных? Струна? Опять же, он отлично работает при передаче пути к файлу XML, и я думаю, что следую указаниям, чтобы этот конструктор передал строку.


person Thufir    schedule 03.02.2020    source источник


Ответы (1)


Он может добавить XML из файла как:

thufir@dur:~/NetBeansProjects/twitterBaseX$ 
thufir@dur:~/NetBeansProjects/twitterBaseX$ ll
total 92
drwxr-xr-x  6 thufir thufir  4096 Feb  3 13:50 ./
drwxr-xr-x 22 thufir thufir  4096 Feb  1 16:05 ../
-rw-rw-r--  1 thufir thufir  1979 Feb  1 21:17 build.gradle
-rw-rw-r--  1 thufir thufir   219 Feb  3 01:04 data.xml
drwxr-xr-x  8 thufir thufir  4096 Feb  3 13:50 .git/
-rw-r--r--  1 thufir thufir   427 Feb  1 16:22 .gitignore
drwxrwxr-x  6 thufir thufir  4096 Jan 30 00:26 .gradle/
drwxrwxr-x  3 thufir thufir  4096 Jan 30 00:24 gradle/
-rwxrwxr-x  1 thufir thufir  5916 Jan 30 00:24 gradlew*
-rw-rw-r--  1 thufir thufir  2941 Jan 30 00:24 gradlew.bat
-rw-r--r--  1 thufir thufir 35149 Jan 30 00:22 LICENSE
-rw-r--r--  1 thufir thufir    51 Jan 30 00:22 README.md
-rw-rw-r--  1 thufir thufir   361 Jan 31 21:55 settings.gradle
drwxrwxr-x  4 thufir thufir  4096 Jan 30 00:24 src/
thufir@dur:~/NetBeansProjects/twitterBaseX$ 
thufir@dur:~/NetBeansProjects/twitterBaseX$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> list
Name                 Resources  Size  Input Path                               
-----------------------------------------------------------------------------
com.w3schools.books  1          6290  https://www.w3schools.com/xml/books.xml  
w3school_data        1          5209  https://www.w3schools.com/xml/note.xml   

2 database(s).
> 
> exit
Enjoy life.
thufir@dur:~/NetBeansProjects/twitterBaseX$ 
thufir@dur:~/NetBeansProjects/twitterBaseX$ gradle clean run

> Task :run
/home/thufir/basex/.basex: writing new configuration file.

BUILD SUCCESSFUL in 3s
4 actionable tasks: 3 executed, 1 up-to-date
thufir@dur:~/NetBeansProjects/twitterBaseX$ 
thufir@dur:~/NetBeansProjects/twitterBaseX$ basex
/home/thufir/basex/.basex: Unknown option 'RESTXQERRORS'.
/home/thufir/basex/.basex: writing new configuration file.
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> list
Name                 Resources  Size   Input Path                               
------------------------------------------------------------------------------
com.w3schools.books  1          6290   https://www.w3schools.com/xml/books.xml  
twitter              15         73551                                           
w3school_data        1          5209   https://www.w3schools.com/xml/note.xml   

3 database(s).
> 
> open twitter
Database 'twitter' was opened in 63.63 ms.
> 
> xquery /
<root>
  <metadata>
    <result_type>recent</result_type>

...

    <notifications>false</notifications>
  </user>
  <favorited>false</favorited>
</root>
Query executed in 292.16 ms.
> 
> exit
Enjoy life.
thufir@dur:~/NetBeansProjects/twitterBaseX$ 

источник:

package basex;

import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.logging.Logger;
import org.basex.core.BaseXException;
import org.basex.core.Context;
import org.basex.core.cmd.Open;
import org.basex.core.cmd.CreateDB;
import org.basex.core.cmd.DropDB;
import org.basex.core.cmd.List;
import org.basex.core.cmd.Set;
import org.json.XML;
import twitter4j.JSONArray;
import twitter4j.JSONException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.basex.core.cmd.Add;

public class DatabaseHelper {

    private static final Logger log = Logger.getLogger(DatabaseHelper.class.getName());
    private Properties properties = new Properties();
    private URL url = null;
    private String databaseName = null;
    private Context context = null;
    private String parserType = null;

    private DatabaseHelper() {
    }

    public DatabaseHelper(Properties properties) {
        this.properties = properties;
    }

    private String wrap(String string) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        stringBuilder.append("<root>");
        stringBuilder.append(string);
        stringBuilder.append("</root>");
        return stringBuilder.toString();
    }

    private void init() throws MalformedURLException, BaseXException {
        log.fine(properties.toString());
        parserType = properties.getProperty("parserType");
        url = new URL(properties.getProperty(parserType + "URL"));
        databaseName = properties.getProperty("databaseName");
        context = new Context();
        list();
    }

    private void list() throws BaseXException {
        log.fine(new List().execute(context));
    }

    private void drop() throws BaseXException {
        new Set("parser", parserType).execute(context);
        new DropDB(databaseName).execute(context);
        list();
    }

    private void create() throws BaseXException, JSONException {
        new Set("parser", parserType).execute(context);
        new CreateDB(databaseName).execute(context);
        new List().execute(context);
        list();
    }

    private void add(JSONArray tweets) throws JSONException, BaseXException, IOException {
        long id = 0L;
        String jsonStringTweet = null;
        org.json.JSONObject jsonObjectTweet = null;
        String stringXml = null;
        String fileName = "tweet.xml";

        new Open(databaseName).execute(context);
        for (int i = 0; i < tweets.length(); i++) {
            jsonStringTweet = tweets.get(i).toString();
            jsonObjectTweet = new org.json.JSONObject(jsonStringTweet);
            stringXml = XML.toString(jsonObjectTweet);
            stringXml = wrap(stringXml);
            write(stringXml,fileName);
            String stringFromFile = read(fileName);
            log.fine(stringFromFile);
            new Add(fileName, stringXml).execute(context);
        }
    }

    public void dropCreateAdd(JSONArray tweets) throws MalformedURLException, BaseXException, JSONException, IOException {
        init();
        drop();
        create();
        add(tweets);
        list();
    }

    private void write(String tweet, String fileName) throws IOException {
        log.fine(tweet);
        FileWriter fileWriter = new FileWriter(fileName);
        fileWriter.write(tweet);
        fileWriter.close();
    }

    private String read(String fileName) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
        return content;
    }
}

но это не показывает, как добавить строку XML в базу данных.

person Thufir    schedule 03.02.2020