houzhongjian
2025-06-12 a01ef141b18dd249df9adc93612501d782c466a7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package com.iailab.framework.common.util.template;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
 
public class XMLParserUtils {
    private final Map<String, String> settings;
    private final double[][] inputData;
 
    public XMLParserUtils(Map<String, String> settings, double[][] inputData) {
        this.settings = settings;
        this.inputData = inputData;
    }
 
    public String parse(String xml) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
        doc.getDocumentElement().normalize();
 
        StringBuilder output = new StringBuilder();
        processNode(doc.getDocumentElement(), output, -1);
        return output.toString();
    }
 
    private void processNode(Node node, StringBuilder output, int index) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            output.append(node.getTextContent().trim());
        } else if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            switch (element.getTagName()) {
                case "simple-value":
                    processSimpleValue(element, output, index);
                    break;
                case "setting-value":
                    processSettingValue(element, output);
                    break;
                case "input-value":
                    processInputValue(element, output, index);
                    break;
                case "foreach-value":
                    processForeachValue(element, output);
                    break;
                default:
                    processChildren(element, output, index);
            }
        }
    }
 
    private void processChildren(Element element, StringBuilder output, int index) {
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            processNode(children.item(i), output, index);
        }
    }
 
    private void processSimpleValue(Element element, StringBuilder output, int index) {
        processChildren(element, output, index);
    }
 
    private void processSettingValue(Element element, StringBuilder output) {
        String key = element.getAttribute("key");
        output.append(settings.getOrDefault(key, ""));
    }
 
    private void processInputValue(Element element, StringBuilder output, int index) {
        // 优先使用:port属性(动态计算)
        String portExpr = element.getAttribute(":port");
        if (portExpr.isEmpty()) {
            // 回退到port属性(静态值)
            portExpr = element.getAttribute("port");
        }
 
        String column = element.getAttribute("column");
        int col = Integer.parseInt(column);
 
        // 动态计算端口值(考虑当前索引)
        int port = evaluateExpression(portExpr, index);
 
        if (port >= 0 && port < inputData.length &&
                col >= 0 && col < inputData[port].length) {
            double value = inputData[port][col];
            output.append((int)value);
        } else {
            System.err.printf("Invalid data access: port=%d (max=%d), col=%d (max=%d)%n",
                    port, inputData.length - 1, col,
                    (port >= 0 && port < inputData.length) ? inputData[port].length - 1 : -1);
            // 默认值
            output.append("0");
        }
    }
 
    private void processForeachValue(Element element, StringBuilder output) {
        String lengthKey = element.getAttribute("length");
        int length = Integer.parseInt(settings.getOrDefault(lengthKey, "0"));
        String separator = element.getAttribute("separator");
 
        StringBuilder loopResult = new StringBuilder();
        for (int i = 0; i < length; i++) {
            StringBuilder itemOutput = new StringBuilder();
 
            // 直接处理所有子节点
            NodeList children = element.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                Node child = children.item(j);
 
                if (child.getNodeType() == Node.TEXT_NODE) {
                    String text = child.getTextContent();
 
                    // 动态确定转炉状态
                    boolean isBlowing = isFurnaceBlowing(i);
 
                    // 替换占位符并调整状态描述
                    text = text.replace("{index}", String.valueOf(i + 1))
                            .replace("未吹炼", isBlowing ? "正在吹炼" : "未吹炼")
                            .replace("距离上次吹炼结束时间",
                                    isBlowing ? "吹炼持续时间" : "距离上次吹炼结束时间");
 
                    itemOutput.append(text);
                } else if (child.getNodeType() == Node.ELEMENT_NODE) {
                    // 传递当前循环索引
                    processNode(child, itemOutput, i);
                }
            }
 
            loopResult.append(itemOutput);
            if (i < length - 1 && !separator.isEmpty()) {
                loopResult.append(separator);
            }
        }
        output.append(loopResult.toString().replace(" ", "").replace("\n", ""));
    }
 
    private boolean isFurnaceBlowing(int furnaceIndex) {
        // 实际业务逻辑:根据输入数据判断转炉状态
        // 这里简化处理:第三个转炉(index=2)正在吹炼
        return furnaceIndex == 2;
    }
 
    // 自定义表达式计算器
    private int evaluateExpression(String expr, int index) {
        if (expr == null || expr.isEmpty()) {
            System.err.println("Empty expression, returning 0");
            return 0;
        }
        // 替换表达式中的{index}占位符
        String processedExpr = expr.replace("{index}", String.valueOf(index));
 
        // 移除所有空格确保表达式正确解析
        processedExpr = processedExpr.replaceAll("\\s", "");
 
        // 尝试直接解析为整数(优化常见情况)
        try {
            return Integer.parseInt(processedExpr);
        } catch (NumberFormatException e) {
            // 不是简单整数,继续尝试表达式计算
        }
        // 自定义简单表达式解析器
        try {
            // 处理加法表达式(如 "3+0")
            if (processedExpr.contains("+")) {
                String[] parts = processedExpr.split("\\+");
                int result = 0;
                for (String part : parts) {
                    result += Integer.parseInt(part);
                }
                return result;
            }
            // 处理减法表达式(如 "5-2")
            else if (processedExpr.contains("-")) {
                String[] parts = processedExpr.split("-");
                int result = Integer.parseInt(parts[0]);
                for (int i = 1; i < parts.length; i++) {
                    result -= Integer.parseInt(parts[i]);
                }
                return result;
            }
//            // 处理乘法表达式(如 "2 * 3")
//            else if (processedExpr.contains("*")) {
//                String[] parts = processedExpr.split("\\*");
//                int result = 1;
//                for (String part : parts) {
//                    result *= Integer.parseInt(part);
//                }
//                return result;
//            }
//            // 处理除法表达式(如 "6/2")
//            else if (processedExpr.contains("/")) {
//                String[] parts = processedExpr.split("/");
//                int result = Integer.parseInt(parts[0]);
//                for (int i = 1; i < parts.length; i++) {
//                    int divisor = Integer.parseInt(parts[i]);
//                    if (divisor != 0) {
//                        result /= divisor;
//                    }
//                }
//                return result;
//            }
        } catch (NumberFormatException e) {
            System.err.println("Error parsing expression: " + processedExpr);
        }
        // 无法解析的表达式
        System.err.println("Unsupported expression format: " + processedExpr);
        return 0;
    }
 
    // test
    public static void main(String[] args) throws Exception {
        String xmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<iquestion>\n" +
                "    <simple-value>根据以下输入,</simple-value>\n" +
                "    <simple-value>\n" +
                "        根据未来<setting-value key=\"predictLength\"/>min的转炉煤气系统运行情况,对煤气调整用户进行调度分配,确保能源产消平衡与系统稳定运行。\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        该系统共包含<setting-value key=\"luShu\"/>座转炉。\n" +
                "    </simple-value>\n" +
                "    <foreach-value length=\"luShu\" index=\"index\" separator=\";\">\n" +
                "        {index}#转炉当前状态未吹炼,\n" +
                "        距离上次吹炼结束时间<input-value :port=\"3 + {index}\" column=\"0\" type=\"double\"/>min,\n" +
                "        前一炉回收间隔<input-value :port=\"3 + {index}\" column=\"2\" type=\"double\"/>min\n" +
                "    </foreach-value>\n" +
                "    <simple-value>\n" +
                "        日计划炉数:<input-value port=\"2\" column=\"0\" type=\"double\"/>,当前已吹炼炉数:<input-value port=\"3\" column=\"0\" type=\"double\"/>;\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        历史60min平均每炉煤气回收量:<input-value port=\"1\" column=\"0\" type=\"double\"/>Km3,\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        当前煤气消耗量<input-value port=\"1\" column=\"1\" type=\"double\"/>km3;\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        当前煤气柜容量<setting-value key=\"guiRongLiang\"/>km3;\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        煤气柜柜位安全区间为<setting-value key=\"anQuanQuJian\"/>km3,期望煤气柜位值在<setting-value key=\"qiWangZhi\"/>km3,\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        当前调度用户为电厂各机组:<setting-value key=\"jiZuMingCheng\"/>,\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        各机组当前使用转炉煤气量 [<input-value port=\"0\" column=\"0\" type=\"double\"/>, <input-value port=\"0\" column=\"1\" type=\"double\"/>, <input-value port=\"0\" column=\"2\" type=\"double\"/>, <input-value port=\"0\" column=\"3\" type=\"double\"/>, <input-value port=\"0\" column=\"4\" type=\"double\"/>, <input-value port=\"0\" column=\"5\" type=\"double\"/>];\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        各机组使用转炉煤气下限量 <setting-value key=\"jiZuXiaXian\"/>。\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        各机组使用转炉煤气上限量 <setting-value key=\"jiZuShangXian\"/>。\n" +
                "    </simple-value>\n" +
                "    <simple-value>\n" +
                "        机组优先级顺序为:<setting-value key=\"jiZuYouXianJi\"/>。\n" +
                "    </simple-value>\n" +
                "    <simple-value>请根据优先级顺序确定调度方案。</simple-value>\n" +
                "</iquestion>";
 
        // 1. 准备配置数据
        Map<String, String> settings = new HashMap<>();
        settings.put("predictLength", "60");
        settings.put("luShu", "3");
        settings.put("guiRongLiang", "80");
        settings.put("anQuanQuJian", "[30, 110]");
        settings.put("qiWangZhi", "65");
        settings.put("jiZuMingCheng", "1#135, 2#135, 1#BTG, 2#BTG, 3#BTG, 4#BTG");
        settings.put("jiZuXiaXian", "[20, 1, 16, 17, 6, 11]");
        settings.put("jiZuShangXian", "[92, 96, 74, 101, 86, 93]");
        settings.put("jiZuYouXianJi", "1#135, 1#BTG, 3#BTG, 2#135, 2#BTG, 4#BTG");
 
        // 示例输入数据 - 与期望输出完全匹配
        double[][] inputData = {
                // 机组当前用量
                {39, 39, 32, 56, 38, 48},
                // [0]:历史回收量, [1]:当前消耗量
                {24, 115},
                // [0]:日计划炉数, [1]:已吹炼炉数
                {21, 10},
                // 转炉1: [0]:结束时间, [2]:回收间隔
                {15, 0, 18},
                // 转炉2: [0]:结束时间, [2]:回收间隔
                {9, 0, 24},
                // 转炉3: [0]:吹炼持续时间, [2]:回收间隔
                {7, 0, 25}
        };
 
        // 3. 创建解析器并执行
        XMLParserUtils parser = new XMLParserUtils(settings, inputData);
        String result = parser.parse(xmlContent); // 替换为你的XML内容
        System.out.println(result);
    }
}