XMLのスクレイピングをGASでしてます
XmlからXmlServiceを使用して取得したくコードを書いています。
取得したいXML
途中まで取得できましたが、
子要素をforeachで繰り返し処理したいのですが、
エラーになってしまいました。
ループしたい要素Subitem1でエラーになります
実現したいこと
最終はスプレッドシートにXMLデータを保存
することです。
下記の表のようにするのが目標です
ArticleCaption | ArticleTitle | ItemTitle | Sentence |
---|---|---|---|
(業務) | 第三条 | 司法書士は、この法律の定めるところにより、他人の依頼を受けて、次に掲げる事務を行うことを業とする。 | |
一 | 登記又は供託に関する手続について代理すること。 |
発生している問題・エラーメッセージ
ReferenceError: item is not defined
該当のソースコード
function mFunction() { let url = 'https://elaws.e-gov.go.jp/api/1/lawdata/昭和二十五年法律第百九十七号'; let xml = UrlFetchApp.fetch(url).getContentText(); let document = XmlService.parse(xml); let root = document.getRootElement(); const applData = root.getChild("ApplData"); const lawFullText = applData.getChild("LawFullText"); const law = lawFullText.getChild("Law"); const lawBody = law.getChild("LawBody"); const mainProvision = lawBody.getChild("MainProvision"); const chapter = mainProvision.getChild("Chapter"); const articles = chapter.getChildren("Article"); articles.forEach(function(article){ const articleCaption = article.getChild("ArticleCaption"); const articleTitle = article.getChild("ArticleTitle"); const paragraphs = article.getChildren("Paragraph"); console.log(articleCaption.getText()); console.log(articleTitle.getText()); if (paragraphs != null){ paragraphs.forEach(function(paragraph){ const paragraphNum = paragraph.getChild("ParagraphNum"); const paragraphSentence = paragraph.getChild("ParagraphSentence"); console.log(paragraphNum.getValue()); console.log(paragraphSentence.getValue()); const items = paragraph.getChildren("Item"); if (items !== null){ items.forEach(function(item){ const itemtitle = item.getChild("ItemTitle"); const itemSentence = item.getChild("ItemSentence"); const columns = itemSentence.getChildren("Column"); console.log("itemtitle"+itemtitle.getText()); if (columns !== null){ console.log("itemSentence"+itemSentence.getValue()); }else{ console.log("columns"+columns.getValue()); } }) } const subitemone = item.getChild("Subitem1"); ●エラーの個所● if (subitemone !== null){ subitemone.forEach(function(subitemone){ const subitemoneTitle = subitemone.getChildren("Subitem1Title"); const subitemoneSentence = subitemoneTitle.getChildren("Subitem1Sentence"); console.log("subitem1Title"+subitemoneTitle.getText()); console.log("ubitem1Sentence"+subitemoneSentence.getValue()); }) } }) } }) }
試したこと
定義の問題って書いてあったので,
Subitemoneに変えたりしましたがエラーが治りませんでした
以前でたエラーのchildとchildrenの違いの試しましたが
できませんでした。
paragraph,
itemで繰り返し処理ができ、同じようにコードを書きました
補足情報(FW/ツールのバージョンなど)
XMLの解析がややこしくてすみません。
どなたかご教授いただけないでしょうか。
itemがないと言われています。
itemがどこで定義されてどのような範囲で使用できるのか考えてみてください。
こういうことはXMLの解析どうのということではなく、基本的な文法の話ですのでそういう基礎から学ばれることをお勧めします。

回答1件
あなたの回答
tips
プレビュー