当前位置: 首页 > 知识库问答 >
问题:

提取XML的某些部分

酆华皓
2023-03-14

我有一个xml,我想提取其中的一部分。但我无法得到它。如果我使用变量并将每个键放入变量中,我可以得到那个部分,但这是一个非常漫长的过程。那幺,是否有任何简短的流程?

下面是 XML :

<?xml version=\"1.0\" encoding=\"UTF-8\"?><xs:nml
xmlns:xs=\"http://www.netgear.com/protocol/transaction/NMLSchema-0.9\" src=\"nas\" dst=\"dpv_1461117132000\" locale=\"en-us\">
<xs:transaction ref-id=\"\" type=\"0\">
    <xs:response ref-id=\"njl_id_1941\" status=\"success\">
        <xs:result>
            <xs:get-s resource-id=\"network_link_list\" resource-type=\"network_link_collection\">
                <network_link_collection>
                    <network_link resource-id=\"eth0\">
                        <link>eth0</link>
                        <ifname>eth0</ifname>
                        <speed>1000</speed>
                        <path/>
                        <duplex>full</duplex>
                        <vlanid>0</vlanid>
                        <iptype>ipv4dhcp</iptype>
                        <ipv6type>ipv6dhcp</ipv6type>
                        <ip>0.0.0.0</ip>
                        <subnet>255.255.255.0</subnet>
                        <broadcast>0.0.0.0</broadcast>
                        <ipv6>::</ipv6>
                        <subnet6>::</subnet6>
                        <prefixlength>64</prefixlength>
                        <ipv6_link>::</ipv6_link>
                        <prefixlength_link>64</prefixlength_link>
                        <mac>6C:B0:CE:1C:CA:AE</mac>
                        <mtu>1500</mtu>
                        <router>0.0.0.0</router>
                        <router6>0.0.0.0</router6>
                        <state>down</state>
                        <dnscollection/>
                        <routecollection/>
                        <ntpcollection/>
                    </network_link>
                </network_link_collection>
            </xs:get-s>
        </xs:result>
    </xs:response>
</xs:transaction>

我想要< code>network link集合中的xml。

共有2个答案

殳飞扬
2023-03-14

Polywhirl先生的回复很棒!!非常感谢!!我只想补充一点,如果你想要提取xml的一部分,但不包括xml header(),像我这样,你必须在“write”方法中添加这个:

transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
栾英资
2023-03-14

您可以相当容易地创建属性键值对的映射。你只需要找到你想要拉出的节点。

NodeList nodeList = doc.getElementsByTagName("network_link").item(0).getChildNodes();
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class ParseResponseXML {
    public static void main(String[] args) {
        try {
            File fXmlFile = getResourceAsFile("resources/Response.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            doc.getDocumentElement().normalize(); // http://stackoverflow.com/questions/13786607

            NodeList nodeList = doc.getElementsByTagName("network_link").item(0).getChildNodes();
            Map<String, String> propertyMap = nodeListToMap(nodeList);

            for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
                System.out.printf("%-18s => %s%n", entry.getKey(), entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Map<String, String> nodeListToMap(NodeList nodeList) {
        Map<String, String> result = new LinkedHashMap<String, String>();
        for (int temp = 0; temp < nodeList.getLength(); temp++) {
            Node node = nodeList.item(temp);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                result.put(element.getTagName(), element.getTextContent());
            }
        }
        return result;
    }

    private static File getResourceAsFile(String resource) throws IOException {
        ClassLoader loader = Parse.class.getClassLoader();
        File resourceFile = null;
        if (loader instanceof URLClassLoader) {
            URLClassLoader urlClassLoader = URLClassLoader.class.cast(loader);
            URL resourceUrl = urlClassLoader.findResource(resource);
            if ("file".equals(resourceUrl.getProtocol())) {
                try {
                    URI uri = resourceUrl.toURI();
                    resourceFile = new File(uri);
                } catch (URISyntaxException e) {
                    IOException ioException = new IOException("Unable to get file through class loader: " + loader);
                    ioException.initCause(e);
                    throw ioException;
                }
            }
        }
        if (resourceFile == null) {
            throw new IOException("Unable to get file through class loader: " + loader);
        }
        return resourceFile;
    }
}

确保您有<代码>

<?xml version="1.0" encoding="UTF-8"?>
<xs:nml xmlns:xs="http://www.netgear.com/protocol/transaction/NMLSchema-0.9"
    src="nas" dst="dpv_1461117132000" locale="en-us">
    <xs:transaction ref-id="" type="0">
        <xs:response ref-id="njl_id_1941" status="success">
            <xs:result>
                <xs:get-s resource-id="network_link_list" resource-type="network_link_collection">
                    <network_link_collection>
                        <network_link resource-id="eth0">
                            <link>eth0</link>
                            <ifname>eth0</ifname>
                            <speed>1000</speed>
                            <path />
                            <duplex>full</duplex>
                            <vlanid>0</vlanid>
                            <iptype>ipv4dhcp</iptype>
                            <ipv6type>ipv6dhcp</ipv6type>
                            <ip>0.0.0.0</ip>
                            <subnet>255.255.255.0</subnet>
                            <broadcast>0.0.0.0</broadcast>
                            <ipv6>::</ipv6>
                            <subnet6>::</subnet6>
                            <prefixlength>64</prefixlength>
                            <ipv6_link>::</ipv6_link>
                            <prefixlength_link>64</prefixlength_link>
                            <mac>6C:B0:CE:1C:CA:AE</mac>
                            <mtu>1500</mtu>
                            <router>0.0.0.0</router>
                            <router6>0.0.0.0</router6>
                            <state>down</state>
                            <dnscollection />
                            <routecollection />
                            <ntpcollection />
                        </network_link>
                    </network_link_collection>
                </xs:get-s>
            </xs:result>
        </xs:response>
    </xs:transaction>
</xs:nml>
link               => eth0
ifname             => eth0
speed              => 1000
path               => 
duplex             => full
vlanid             => 0
iptype             => ipv4dhcp
ipv6type           => ipv6dhcp
ip                 => 0.0.0.0
subnet             => 255.255.255.0
broadcast          => 0.0.0.0
ipv6               => ::
subnet6            => ::
prefixlength       => 64
ipv6_link          => ::
prefixlength_link  => 64
mac                => 6C:B0:CE:1C:CA:AE
mtu                => 1500
router             => 0.0.0.0
router6            => 0.0.0.0
state              => down
dnscollection      => 
routecollection    => 
ntpcollection      => 

如果要展开节点,可以执行以下操作。

import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class ParseResponseXML {
    public static void main(String[] args) {
        try {
            Document inputDoc = load("resources/Response.xml");
            Document outputDoc = unwrap(inputDoc, "network_link_collection");

            write(outputDoc, "NetworkLinkCollection.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Document load(String resource) throws IOException, ParserConfigurationException, SAXException {
        File file = getResourceAsFile(resource);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        return dBuilder.parse(file);
    }

    public static void write(Document doc, String filename) throws TransformerException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filename));
        // StreamResult result = new StreamResult(System.out); // Output to console.
        transformer.transform(source, result);
    }

    public static Document unwrap(Document doc, String tagName) throws ParserConfigurationException {
        Node node = doc.getElementsByTagName(tagName).item(0);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document result = dBuilder.newDocument();
        Node importNode = result.importNode(node, true);
        result.appendChild(importNode);
        return result;
    }

    private static File getResourceAsFile(String resourceName) throws IOException {
        ClassLoader loader = ParseResponseXML.class.getClassLoader();
        File resourceFile = null;
        if (loader instanceof URLClassLoader) {
            URLClassLoader urlClassLoader = URLClassLoader.class.cast(loader);
            URL resourceUrl = urlClassLoader.findResource(resourceName);
            if ("file".equals(resourceUrl.getProtocol())) {
                try {
                    URI uri = resourceUrl.toURI();
                    resourceFile = new File(uri);
                } catch (URISyntaxException e) {
                    IOException ioException = new IOException("Unable to get file through class loader: " + loader);
                    ioException.initCause(e);
                    throw ioException;
                }
            }
        }
        if (resourceFile == null) {
            throw new IOException("Unable to get file through class loader: " + loader);
        }
        return resourceFile;
    }
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<network_link_collection>
    <network_link resource-id="eth0">
        <link>eth0</link>
        <ifname>eth0</ifname>
        <speed>1000</speed>
        <path />
        <duplex>full</duplex>
        <vlanid>0</vlanid>
        <iptype>ipv4dhcp</iptype>
        <ipv6type>ipv6dhcp</ipv6type>
        <ip>0.0.0.0</ip>
        <subnet>255.255.255.0</subnet>
        <broadcast>0.0.0.0</broadcast>
        <ipv6>::</ipv6>
        <subnet6>::</subnet6>
        <prefixlength>64</prefixlength>
        <ipv6_link>::</ipv6_link>
        <prefixlength_link>64</prefixlength_link>
        <mac>6C:B0:CE:1C:CA:AE</mac>
        <mtu>1500</mtu>
        <router>0.0.0.0</router>
        <router6>0.0.0.0</router6>
        <state>down</state>
        <dnscollection />
        <routecollection />
        <ntpcollection />
    </network_link>
</network_link_collection>
 类似资料:
  • 提取和修改位 从压缩的final_value中的某个位置选取n个位,并写入任意位置,而不修改uint16_t test_bit=0x3048的原始内容。预期输出=0x5048 例如:从final_val选取010(位置17的3位),然后写入任意位置(位置11) 0x3048=0111 0000 0100 1000 0x5048=0101 0000 0100 1000 示例 A: 粗体是提取的,我们

  • 我一直试图在多行文本中提取SQL查询,但总是得到错误的输出。 如何在一个或三个引号之间获得文本? 注意:在第一个完整引号,,,之前和之后都可以有任何东西,我只对在引号之间找到第一个文本感兴趣。 我的尝试: 所需输出:

  • 问题内容: 我喜欢Django,但对于特定的应用程序,我只想使用其中的一部分,但是我对Django在内部的工作方式还不够熟悉,因此也许有人可以为我指明正确的方向查看。 具体来说,我想使用: 模型和数据库抽象 该缓存API,但我想通过缓存来避免数据库查询,而不是HTML生成,并且由于在Django的缓存框架适用于后者,我不 知道是否还没有这真的合适。 我不会使用: Templating urlcon

  • 我想知道是否可以使用此方法忽略字段,因为我有一个要忽略的字段列表,在同一个类中,那么我该如何做呢? 我正在使用 谢谢

  • 我正在尝试通过url读取pdf。我遵循了许多stackoverflow建议并使用PyPdf2 FileReader从pdf中提取文本。我的代码如下所示: 我能够成功地提取第一个链接的文本。但是如果我对第二个pdf使用相同的程序。我没有收到任何短信。页码和文档信息似乎出现了。 我尝试通过终端从Pdfminer中提取文本,并能够从第二个pdf中提取文本。 你知道pdf有什么问题吗?或者我使用的库有缺点

  • 问题内容: 如何用另一部分替换字符串的特定部分? 输入字符串: 如何用其他方式更改字符串中的全部? 我认为我需要一个循环,但是我不确定如何使用它。 问题答案: 或者更精确地回答您的问题: