我已经从 XML 文件中收集了一些数据,现在正在尝试编辑这些数据以使其适合我的程序。我收集的数据说明了给定参数的最小值和最大值,但我只对最小值或最大值感兴趣。
XML 数据源如下所示:
<tolerated>
<UMIN2> [ 181.2 186.8 ] </UMIN2>
<T_UMIN2> [ 0.4 0.6 ] </T_UMIN2>
<UMIN1> [ 197 203 ] </UMIN1>
<T_UMIN1> [ 2.4 2.6 ] </T_UMIN1>
<UMAX1> [ 249.2 256.8 ] </UMAX1>
<T_UMAX1> [ 0.9 1.1 ] </T_UMAX1>
<UMAX2> [ 260 268 ] </UMAX2>
<T_UMAX2> [ 0.4 0.6 ] </T_UMAX2>
</tolerated>
我已经让我的程序通过此代码将此数据加载到名为 tol 的字符串中
public static String tolerance() throws SAXException, IOException, ParserConfigurationException, XPathExpressionException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(O1.replace("\\","\\\\"));
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
String tTemp = new String();
XPathExpression expr1 = xpath.compile("ptfGen/body/gridCode/"+header2.substring(31,header2.length()-23)+"/tolerated");
Node nodeGettingChanged1 = (Node) expr1.evaluate(doc, XPathConstants.NODE);
String toldata = new String();
NodeList childNodes1 = nodeGettingChanged1.getChildNodes();
for (int i = 0; i != childNodes1.getLength(); i++)
{
Node child = (Node) childNodes1.item(i);
if (!(child instanceof Element))
continue;
if (child.getNodeName().equals("tolerated"));{
toldata = child.getFirstChild().getNodeValue();
tTemp += toldata.substring(3,toldata.length()-3).replace(" ", "\n") + "\n";
}
tol = tTemp;
}
return tTemp;
}
这为我提供了所有带有换行符分隔的值。
我现在的问题是我可以/如何删除所有其他条目,以便我只有最小值或最大值?´
我现在得到的输出类似于
tol = {"181.2\n186.8\n0.4\n0.6\n197\n........"};
我正在寻找的是
tol = {"181.2\n0.4\n197\n........"};
最佳答案
如果最小值始终位于第一,最大值始终位于第二。
你需要做的就是改变
tTemp += toldata.substring(3,toldata.length()-3).replace(" ", "\n") + "\n";
至
tTemp += toldata.substring(3,toldata.length()-3).split(" ")[c] + "\n";
其中 c
对于第一个(最小值)为 0,对于第二个(最大值)为 1。
或更简单的
tTemp += toldata.split(" ")[c] + "\n";
其中 c
在相应情况下为 2 或 3。
这当然假设字符串始终采用精确的形式:"[ number number ] "
(始终在完全相同的位置具有完全相同数量的空格)。一个简单的regular expression "\\s+"
而不是 ""
将允许一个或多个空格,即:
tTemp += toldata.split("\\s+")[c] + "\n";
\s
表示空白,+
表示一个或多个。额外的 \
是为了转义编译器的 \
。
关于java - 删除所有其他字符串条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17832127/