[英]create basic line breaks with an Xpath Expression from Java to XML file
學習如何編程Stack Overflow的Throghout提供了豐富的信息,並且是學習如何弄清楚不同事物的主要方法。 但是對於這個問題,經過幾天的搜索並空手而歸,我決定創建我的第一篇文章。
問題是,使用Xpath的Node.setTextContent從Java字符串在XML文件中創建多行值。 它寫入Xpath報告為元素節點的XML文件中的value標記。 現在,當將字符串值寫入節點時,確實確實將字符串值寫入節點,但是它只是一個長字符串值,因為根據API的setTextContent方法不會解析字符串中的任何內容,而只是寫入文本。 我要寫入的數據示例如下:(編輯為2-16,只是注意到format選項未顯示主要帖子)的格式如下,街道,城市州和電話均已分解,如下所示(行之間沒有空格)以匹配第一個xml代碼示例中列出的格式。
生動大道496號
州薩摩市11111
111-222-3333
將Java字符串寫入xml文件時,其輸入為:496 VividAve。 州,一些市,電話:11111 111-222-3333
從父程序(不是我的Java應用程序)創建的節點的示例是:
<field sid="ADDRESS">
<itemlocation>
<ae>
<ae>absolute</ae>
<ae>33</ae>
<ae>168</ae>
</ae>
</itemlocation>
<value>496 Vivid Ave.
Some City, State, 11111
111-222-3333</value>
<borderwidth>0</borderwidth>
<fontinfo>
<ae>Times New Roman</ae>
<ae>10</ae>
<ae>plain</ae>
</fontinfo>
<scrollhoriz>wordwrap</scrollhoriz>
<scrollvert>fixed</scrollvert>
<format>
<ae>string</ae>
<ae>optional</ae>
</format>
<acclabel>6. leave address.
enter street, city, state, zip code and phone number.
</acclabel>
<size>
<ae>35</ae>
<ae>3</ae>
</size>
<previous>FIELD5</previous>
<next>ORDINARY</next>
</field>
當我運行我的應用程序時,原始xml數據的輸出看起來像這樣:
<field sid="ADDRESS">
<itemlocation>
<ae>
<ae>absolute</ae>
<ae>33</ae>
<ae>168</ae>
</ae>
</itemlocation>
<value>496 Vivid Ave. Some City, State, 11111 111-222-3333</value>
<borderwidth>0</borderwidth>
<fontinfo>
<ae>Times New Roman</ae>
<ae>10</ae>
<ae>plain</ae>
</fontinfo>
<scrollhoriz>wordwrap</scrollhoriz>
<scrollvert>fixed</scrollvert>
<format>
<ae>string</ae>
<ae>optional</ae>
</format>
<acclabel>6. leave address.
enter street, city, state, zip code and phone number.
</acclabel>
<size>
<ae>35</ae>
<ae>3</ae>
</size>
<previous>FIELD5</previous>
<next>ORDINARY</next>
</field>
我嘗試手動在字符串中輸入換行符和回車符的轉義字符,它所做的只是打印代碼值而不是值。
當父程序讀取我的Java代碼時,它不會在單獨的行中分解地址和電話號碼。
我正在使用的Java看起來像:
public void setFieldValue(String sid, String value){
Node resultNode = null;
XPath xPath = XPathFactory.newInstance().newXPath();
try{
resultNode = (Node)xPath.evaluate(makeFieldString(sid), doc,XPathConstants.NODE);
}catch(XPathExpressionException xpee){System.out.println(xpee + "Could not retrive node");}
if (resultNode != null){
resultNode.setTextContent(value);
}
else System.out.println("Epic fail");
}
public String makeFieldString(String sid){
String output=null;
if (sid.equals("POPUP2")){
output="//popup[@sid='" + sid + "']/value";
}
else{
output= "//field[@sid='" + sid + "']/value";
}
return output;
}
如果有人對如何使Java字符串包含換行符有任何想法,則setTextContent將識別出該行,我會予以考慮。 我已經拋棄了嘗試使用文本規范化和空白數據的想法,但是並不確定如何實現它,也不確定這些方法是否會從setTextContent方法中剝離出來。
謝謝你的幫助! 我希望我的問題足夠清楚,不要被解雇!
我在http://xpath.alephzarro.com/content/cheatsheet.html上找到了一個xpather備忘單,其中顯示了正則表達式中的特殊字符,而Xpath不會插入換行符的unicoode值,但它確實可以識別\\ n行,現在地址塊已正確格式化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.