LoginSignup
5
5

More than 5 years have passed since last update.

XML をパースする(C++/CX, C#版)

Last updated at Posted at 2014-01-05

XML をパースする のC++/CX版。
Windows::Data::Xml::Dom 名前空間にある XmlDocument を利用する。
DOMパーサであるので、XMLの木構造がXmlDocumentに構築される。
その中から特定のtagを持つElementを取得し、アトリビュートを抽出する。

#include <locale>
#include <iostream>
#include <string>

using namespace Platform;
using namespace Windows::Data::Xml::Dom;

template<typename Function>
void collect(XmlDocument^ doc, String^ tag, String^ attr, Function func) {
    // 指定したtag名を持つElementを探す
    XmlNodeList^ nodes = doc->GetElementsByTagName(tag);
    if ( nodes == nullptr ) return;
    for ( unsigned int i = 0; i < nodes->Size; ++i ) {
        XmlElement^ elm = safe_cast<XmlElement^>(nodes->GetAt(i));
        // アトリビュートを手に入れる
        String^ value = elm->GetAttribute(attr);
        if ( value != nullptr ) func(std::wstring(value->Begin(), value->End()));
    }
}

using namespace std;

int main(Array<String^>^) {
    String^ xhtml =
       L"<?xml version='1.0' ?>" 
       L"<html><body>"
       L"  <a href=\"http://qiita.com/episteme\">επιστημη(1)</a>"
       L"  <a href=\"http://blogs.wankuma.com/episteme\">επιστημη(2)</a>"
       L"  <img src=\"https://pbs.twimg.com/profile_images/54608127/epi_normal.jpg\"/>"
       L"</body></html>";

    XmlDocument^ doc = ref new XmlDocument();
    doc->LoadXml(xhtml);

    wcout.imbue(locale("japanese"));
    collect(doc, L"a",   L"href", [](const wstring& value) { wcout << value << endl;});
    collect(doc, L"img", L"src",  [](const wstring& value) { wcout << value << endl;});

}

同様にC#だと:

using System;
using System.Xml;

class Program {
    static void collect(XmlDocument doc, string tag, string attr, Action<String> func) {
        XmlNodeList nodes = doc.GetElementsByTagName(tag);
        if ( nodes == null ) return;
        for ( int i = 0; i < nodes.Count; ++i ) {
            XmlElement elm = nodes[i] as XmlElement;
            string value = elm.GetAttribute(attr);
            if ( value != null ) func(value);
        }
    }

    static void Main(string[] args) {
        string xhtml =
          "<?xml version='1.0' ?>" 
        + "<html><body>"
        + "  <a href=\"http://qiita.com/episteme\">επιστημη(1)</a>"
        + "  <a href=\"http://blogs.wankuma.com/episteme\">επιστημη(2)</a>"
        + "  <img src=\"https://pbs.twimg.com/profile_images/54608127/epi_normal.jpg\"/>"
        + "</body></html>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xhtml);

        collect(doc, "a",   "href", (val) => Console.WriteLine(val));
        collect(doc, "img", "src" , (val) => Console.WriteLine(val));
    }
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5