Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ルビ振りAPIようXMLパース
// JavaScript source code
xml = '<ResultSet xmlns="urn:yahoo:jp:jlp:FuriganaService" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:yahoo:jp:jlp:FuriganaService https://jlp.yahooapis.jp/FuriganaService/V1/furigana.xsd">\n<Result>\n<WordList>\n<Word>\n<Surface>漢字</Surface>\n<Furigana>かんじ</Furigana>\n<Roman>kanzi</Roman>\n</Word>\n<Word>\n<Surface>かな交じり</Surface>\n<Furigana>かなまじり</Furigana>\n<Roman>kanamaziri</Roman>\n<SubWordList>\n<SubWord>\n<Surface>かな</Surface>\n<Furigana>かな</Furigana>\n<Roman>kana</Roman>\n</SubWord>\n<SubWord>\n<Surface>交</Surface>\n<Furigana>ま</Furigana>\n<Roman>ma</Roman>\n</SubWord>\n<SubWord>\n<Surface>じり</Surface>\n<Furigana>じり</Furigana>\n<Roman>ziri</Roman>\n</SubWord>\n</SubWordList>\n</Word>\n<Word>\n<Surface>文</Surface>\n<Furigana>ぶん</Furigana>\n<Roman>bun</Roman>\n</Word>\n<Word>\n<Surface>に</Surface>\n</Word>\n<Word>\n<Surface>ふりがな</Surface>\n</Word>\n<Word>\n<Surface>を</Surface>\n</Word>\n<Word>\n<Surface>振る</Surface>\n<Furigana>ふる</Furigana>\n<Roman>huru</Roman>\n<SubWordList>\n<SubWord>\n<Surface>振</Surface>\n<Furigana>ふ</Furigana>\n<Roman>hu</Roman>\n</SubWord>\n<SubWord>\n<Surface>る</Surface>\n<Furigana>る</Furigana>\n<Roman>ru</Roman>\n</SubWord>\n</SubWordList>\n</Word>\n<Word>\n<Surface>こと</Surface>\n</Word>\n<Word>\n<Surface>。</Surface>\n</Word>\n</WordList>\n</Result>\n</ResultSet>'
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(xml, "application/xml");
var ruby = [
['', '', ''],//青空文庫ルビ
['[[rb:', ' > ', ']]'],//pixiv
['{', '}(', ')'],//BCCKS
['{', '|', '}'],//でんでんマークダウン
['<ruby>', '<rt>', '</rt></ruby>'],//HTML5
['\\ruby{', '}{', '}'],//LaTeX
];
r = 2;
var str = "";
function addruby(ruby, r, dom) { // タグ名がWordのエレメント取得
var root = dom.documentElement;
var elements = root.getElementsByTagName("Word");
// Alert(elements.length);
//
for (var i = 0; i < elements.length; i++) {
// エレメント取得
var element = elements[i];
// 子取得
var child = element.children;
switch (element.children.length) {
case 1: str += child[0].textContent; break;
case 3:
if (child[0].textContent == child[1].textContent) {
str += child[0].textContent;
} else {
str += ruby[r][0] + child[0].textContent + ruby[r][1] + child[1].textContent + ruby[r][2];
} break;
case 4: var subwords = child[3].children;
for (var j = 0; j < subwords.length; j++) {
var subword = subwords[j];
var subchild = subword.children;
switch (subchild.length) {
case 1: str += subchild[0].textContent; break;
case 3:
if (subchild[0].textContent == subchild[1].textContent) {
str += subchild[0].textContent;
} else {
str += ruby[r][0] + subchild[0].textContent + ruby[r][1] + subchild[1].textContent + ruby[r][2];
}
break;
}
}
break;
}
}
return str;
}
str = addruby(ruby, r, oDOM);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.