この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

Newer Version Available

This content describes an older version of this product. View Latest

DOM を使用した XML の読み取りと書き込み

Apex では、DOM (ドキュメントオブジェクトモデル) を使用して XML コンテンツを操作できるクラスを提供します。

DOM クラスを使用して、XML コンテンツを解析または生成できます。これらのクラスを使用して、XML コンテンツを処理できます。ある一般的なアプリケーションでは、このクラスを使用して HttpRequest で作成されたリクエストボディを生成するか、HttpResponse がアクセスした応答を解析します。DOM は、XML ドキュメントをノードの階層として示します。分岐ノードで子ノードがあるノードもあれば、葉ノードで子ノードがないものもあります。深度が最大 50 ノードのネストされた XML コンテンツを解析できます。

DOM クラスは Dom 名前空間に含まれます。

Document クラスを使用して、XML ドキュメントの本文の内容を処理します。

XmlNode クラスを使用して XML ドキュメントのノードを処理します。

Document クラスを使用して、XML コンテンツを処理します。ある一般的なアプリケーションでは、このクラスを使用して、HttpRequest のリクエストボディを作成するか、HttpResponse がアクセスした応答を解析します。

XML 名前空間

XML 名前空間は、URI 参照で識別される名前のコレクションで XML ドキュメントで使用され、要素の種類や属性名を一意に特定します。XML 名前空間の名前は修飾名として示される場合があり、コロンを使用して、名前を名前空間プレフィックスとローカルの部分に分割します。URI 参照に対応付けられたプレフィックスは、名前空間を選択します。管理された URI 名前空間とドキュメント独自の名前空間を組み合わせて、一意の識別子を作成します。

次の XML 要素には、http://my.name.space の名前空間と myprefix のプレフィックスがあります。

1<sampleElement xmlns:myprefix="http://my.name.space" />

次の例では、XML 要素に 2 つの属性があります。

  • 最初の属性には、dimension のキーがあります。値は 2 です。
  • 2 番目の属性には、http://ns1 のキー名前空間があります。値名前空間は http://ns2、キーは foo、値は bar です。
1<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

Document の例

この例では、parseResponseDom に渡される url 引数が次の XML 応答を返すと想定します。

1<address>
2    <name>Kirk Stevens</name>
3    <street1>808 State St</street1>
4    <street2>Apt. 2</street2>
5    <city>Palookaville</city>
6    <state>PA</state>
7    <country>USA</country>
8</address>

次の例では、DOM クラスを使用して GET リクエストボディで返される XML 応答をどのように解析するかを示しています。

1public class DomDocument {
2 
3    // Pass in the URL for the request
4    // For the purposes of this sample,assume that the URL
5    // returns the XML shown above in the response body
6    public void parseResponseDom(String url){
7        Http h = new Http();
8        HttpRequest req = new HttpRequest();
9        // url that returns the XML in the response body
10        req.setEndpoint(url);
11        req.setMethod('GET');
12        HttpResponse res = h.send(req);
13        Dom.Document doc = res.getBodyDocument();
14        
15        //Retrieve the root element for this document.
16        Dom.XMLNode address = doc.getRootElement();
17        
18        String name = address.getChildElement('name', null).getText();
19        String state = address.getChildElement('state', null).getText();
20        // print out specific elements
21        System.debug('Name: ' + name);
22        System.debug('State: ' + state);
23        
24        // Alternatively, loop through the child elements.
25        // This prints out all the elements of the address
26        for(Dom.XMLNode child : address.getChildElements()) {
27           System.debug(child.getText());
28        }
29    }
30}

XML ノードの使用

XmlNode クラスを使用して XML ドキュメントのノードを処理します。DOM は、XML ドキュメントをノードの階層として示します。分岐ノードで子ノードがあるノードもあれば、葉ノードで子ノードがないものもあります。

Apex で使用できるさまざまな種類の DOM ノードがあります。XmlNodeType は、これらの種類の列挙です。値は次のとおりです。

  • COMMENT
  • ELEMENT
  • TEXT

XML ドキュメントでは、要素とノードを区別することが重要です。次に、XML の簡単な例を示します。

1<name>
2    <firstName>Suvain</firstName>
3    <lastName>Singh</lastName>
4</name>

この例には、namefirstNamelastName の 3 つの XML 要素が含まれています。namefirstNamelastName の 3 つの要素ノード、SuvainSingh の 2 つのテキストノード、合計 5 つのノードが含まれています。要素ノード内のテキストは、個別のテキストノードとみなされます。

すべての enum で共有されるメソッドの詳細は、「Enum メソッド」を参照してください。

XmlNode の例

この例では、XmlNode メソッドおよび名前空間を使用して XML 要求を作成する方法を示します。

1public class DomNamespaceSample
2{
3    public void sendRequest(String endpoint)
4    {
5        // Create the request envelope
6        DOM.Document doc = new DOM.Document();
7        
8        String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
9        String xsi = 'http://www.w3.org/2001/XMLSchema-instance';
10        String serviceNS = 'http://www.myservice.com/services/MyService/';
11        
12        dom.XmlNode envelope
13            = doc.createRootElement('Envelope', soapNS, 'soapenv');
14        envelope.setNamespace('xsi', xsi);
15        envelope.setAttributeNS('schemaLocation', soapNS, xsi, null);
16        
17        dom.XmlNode body
18            = envelope.addChildElement('Body', soapNS, null);
19        
20        body.addChildElement('echo', serviceNS, 'req').
21           addChildElement('category', serviceNS, null).
22           addTextNode('classifieds');
23        
24        System.debug(doc.toXmlString());
25        
26        // Send the request
27        HttpRequest req = new HttpRequest();
28        req.setMethod('POST');
29        req.setEndpoint(endpoint);
30        req.setHeader('Content-Type', 'text/xml');
31        
32        req.setBodyDocument(doc);
33        
34        Http http = new Http();
35        HttpResponse res = http.send(req);
36        
37        System.assertEquals(200, res.getStatusCode());
38        
39        dom.Document resDoc = res.getBodyDocument();
40        
41        envelope = resDoc.getRootElement();
42        
43        String wsa = 'http://schemas.xmlsoap.org/ws/2004/08/addressing';
44        
45        dom.XmlNode header = envelope.getChildElement('Header', soapNS);
46        System.assert(header != null);
47        
48        String messageId
49            = header.getChildElement('MessageID', wsa).getText();
50        
51        System.debug(messageId);
52        System.debug(resDoc.toXmlString());
53        System.debug(resDoc);
54        System.debug(header);
55        
56        System.assertEquals(
57         'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous',
58         header.getChildElement(
59           'ReplyTo', wsa).getChildElement('Address', wsa).getText());
60        
61        
62        System.assertEquals(
63          envelope.getChildElement('Body', soapNS).
64              getChildElement('echo', serviceNS).
65              getChildElement('something', 'http://something.else').
66              getChildElement(
67                'whatever', serviceNS).getAttribute('bb', null),
68                'cc');
69        
70        System.assertEquals('classifieds',
71          envelope.getChildElement('Body', soapNS).
72              getChildElement('echo', serviceNS).
73              getChildElement('category', serviceNS).getText());
74    }
75}