├── LICENSE
├── README.md
├── build_remote_docs_catalog.py
├── calculation_linkbase_traversal.py
├── csharp
├── CalculationLinkbaseTraversal
│ ├── CalculationLinkbaseTraversal.csproj
│ ├── CalculationLinkbaseTraversal.sln
│ └── Program.cs
├── DimensionalRelationshipSetTraversal
│ ├── DimensionalRelationshipSetTraversal.csproj
│ ├── DimensionalRelationshipSetTraversal.sln
│ └── Program.cs
├── FindDuplicateContexts
│ ├── FindDuplicateContexts.csproj
│ ├── FindDuplicateContexts.sln
│ └── Program.cs
├── FindDuplicateUnits
│ ├── FindDuplicateUnits.csproj
│ ├── FindDuplicateUnits.sln
│ └── Program.cs
├── FindFactsByName
│ ├── FindFactsByName.csproj
│ ├── FindFactsByName.sln
│ └── Program.cs
├── FindFactsWithSameAspects
│ ├── FindFactsWithSameAspects.csproj
│ ├── FindFactsWithSameAspects.sln
│ └── Program.cs
├── InstanceStatistics
│ ├── InstanceStatistics.csproj
│ ├── InstanceStatistics.sln
│ └── Program.cs
├── OIMReportBuilderExample
│ ├── OIMReportBuilderExample.cs
│ ├── OIMReportBuilderExample.csproj
│ └── OIMReportBuilderExample.sln
├── PresentationLinkbaseTraversal
│ ├── PresentationLinkbaseTraversal.csproj
│ ├── PresentationLinkbaseTraversal.sln
│ └── Program.cs
├── README.md
├── XBRLImportTest
│ ├── App.config
│ ├── Program.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── XBRLImportTest.csproj
│ └── XBRLImportTest.sln
├── XBRLTablesToExcel
│ ├── App.config
│ ├── DefaultTableStyle.cs
│ ├── ExcelWriter.cs
│ ├── ITableStyle.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── README.md
│ ├── Report.cs
│ ├── Table.cs
│ ├── TableTree.cs
│ ├── XbrlTablesToExcel.cs
│ ├── XbrlTablesToExcel.csproj
│ ├── XbrlTablesToExcel.sln
│ ├── XbrlUtils.cs
│ └── packages.config
└── XPathXQueryXslt
│ ├── INTRO.md
│ ├── XPathApiExamples
│ ├── Directory.build.props
│ ├── ExternalFunction
│ │ ├── ExternalFunction.cs
│ │ └── ExternalFunction.csproj
│ ├── ExternalVariables
│ │ ├── ExternalVariables.cs
│ │ └── ExternalVariables.csproj
│ ├── GettingStarted
│ │ ├── GettingStarted.cs
│ │ └── GettingStarted.csproj
│ ├── InitialContextItem
│ │ ├── InitialContextItem.cs
│ │ └── InitialContextItem.csproj
│ ├── InitialContextXmlDocument
│ │ ├── InitialContextXmlDocument.cs
│ │ └── InitialContextXmlDocument.csproj
│ ├── NamespacePrefixes
│ │ ├── NamespacePrefixes.cs
│ │ └── NamespacePrefixes.csproj
│ ├── README.md
│ ├── TraceMsg
│ │ ├── TraceMsg.cs
│ │ └── TraceMsg.csproj
│ └── XPathApiExamples.sln
│ ├── XQueryApiExamples
│ ├── Directory.build.props
│ ├── README.md
│ ├── XQueryApiExamples.sln
│ └── XQuerySample
│ │ ├── XQuerySample.cs
│ │ └── XQuerySample.csproj
│ └── XSLTApiExamples
│ ├── Directory.build.props
│ ├── QuickIntroSample
│ ├── Program.cs
│ ├── Program.csproj
│ └── QuickIntroSample.sln
│ ├── README.md
│ ├── XSLTApiExamples.sln
│ └── XSLTSample
│ ├── XSLTSample.cs
│ └── XSLTSample.csproj
├── custom_validation.py
├── dimensional_relationship_set_traversal.py
├── entry_points.py
├── generate_html_from_table_linkbase.py
├── generate_html_from_table_linkbase_oim.py
├── instance_statistics.py
├── oim_reportbuilder_example.py
├── presentation_linkbase_traversal.py
├── script_parameters.py
├── write_to_file.py
├── xbrl_testsuite.py
├── xml_as_html.py
├── xml_pretty_print.py
├── xml_traversal.py
└── xpath_xquery_xslt_py
├── INTRO.md
├── README.md
└── xslt_demo_sample.py
/README.md:
--------------------------------------------------------------------------------
1 | # RaptorXML-Examples
2 | Examples for using the [Python v2.4 API](http://manual.altova.com/RaptorXML/pyapiv2/html/) of [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html).
3 |
4 | **NOTE:** *The examples for other language bindings are located in sub-folders.*
5 |
6 | ## Python examples
7 | Each script includes a short documentation and a sample invocation command line at the top a.
8 |
9 | ##### build_remote_docs_catalog.py
10 | Create `catalog.xml` files for remote files.
11 |
12 | ##### calculation_linkbase_traversal.py
13 | Print out all the calculation networks found in the DTS as simple trees
14 |
15 | ##### custom_validation.py
16 | Demonstrates how to add additional validation rules and report custom errors.
17 |
18 | ##### dimensional_relationship_set_traversal.py
19 | Print out all the DRS (Dimensional relationship set) networks found in the DTS as simple trees.
20 |
21 | ##### entry_points.py
22 | A minimal stub implementation for each entry point function in RaptorXML Python API v2.
23 |
24 | ##### generate_html_from_table_linkbase.py
25 | Generate HTML tables according to the layout specified in the XBRL Table linkbase.
26 |
27 | ##### instance_statistics.py
28 | Print out some statistics about the instance and its supporting DTS.
29 |
30 | ##### presentation_linkbase_traversal.py
31 | Print out all the presentation networks found in the DTS as simple trees.
32 |
33 | ##### script_parameters.py
34 | Demonstrates how to supply additional parameters to RaptorXML Python API v2 scripts.
35 |
36 | ##### write_to_file.py
37 | Example how to generate additional output files from a Python API v2 script.
38 |
39 | ##### xbrl_testsuite.py
40 | Executes the XBRL 2.1 conformance test suite.
41 |
42 | ##### xml_traversal.py
43 | Demonstrates how to navigate through an XML Infoset tree.
44 |
45 | ##### xml_as_html.py
46 | Example how to convert XML documents to simple HTML.
47 |
48 | ##### xml_pretty_print.py
49 | Simple pretty printer for XML documents.
50 |
51 | ##### xpath_xquery_xslt_py
52 | Demonstrates the XPath, XQuery, XSLT engine usage in python environment.
53 |
54 | For more information on the Python v2.4 API, please refer to this [documentation](http://manual.altova.com/RaptorXML/pyapiv2/html/).
55 |
--------------------------------------------------------------------------------
/build_remote_docs_catalog.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | import os
18 | import urllib.request
19 | import urllib.parse
20 | from altova import xml, xsd
21 |
22 | # This script downloads all remote parts of the schema as a whole / discoverable taxonomy set.
23 | # The target directory for the downloaded documents can be specified with the script-param target.
24 | # If no target is specified the documents are stored in the subfolder /output in job.output_dir.
25 | # If any document was downloaded, a catalog containing uri mappings for each downloaded
26 | # document is created. It is stored in the target directory and called catalog.xml.
27 | #
28 | # Example: raptorxml xsd --script=build_remote_docs_catalog.py
29 | # http://www.w3.org/MarkUp/Forms/2007/XForms-11-Schema.xsd
30 |
31 |
32 | # string templates for catalog ###########################################
33 | g_CatalogTemplate = """
34 |
38 | %(mappings)s
39 |
40 | """
41 | g_uriMappingTemplate = """"""
42 |
43 |
44 | # helper functions #######################################################
45 | def writeDoc(path, content, mode="wb"):
46 | dir, file = os.path.split(path)
47 | if not os.path.exists(dir):
48 | os.makedirs(dir)
49 | f = open(path, mode)
50 | f.write(content)
51 | f.close()
52 |
53 |
54 | def downloadDoc(url, target):
55 | content = urllib.request.urlopen(url).read()
56 | writeDoc(target, content, "wb")
57 |
58 |
59 | def createCatalog(uriMappings, catalogPath):
60 | catalogDir = os.path.dirname(catalogPath)
61 | lines = []
62 | for source, target in uriMappings.items():
63 | target = os.path.relpath(target, catalogDir)
64 | lines.append(g_uriMappingTemplate %
65 | {"source": source, "target": target})
66 | catalogContent = g_CatalogTemplate % {"mappings": "\n ".join(lines)}
67 | writeDoc(catalogPath, catalogContent, "w")
68 |
69 |
70 | def createUniqueFileName(targetDir, urlParts):
71 | path = urlParts.path[1:] if urlParts.path.startswith(
72 | "/") else urlParts.path
73 | targetFileName = os.path.join(targetDir, urlParts.netloc, path)
74 | head, tail = os.path.split(targetFileName)
75 | i = 1
76 | while os.path.exists(targetFileName):
77 | nextTail = "%d_%s" % (i, tail)
78 | i += 1
79 | targetFileName = os.path.join(head, nextTail)
80 | return targetFileName
81 |
82 |
83 | def download_docs(docs, targetDir):
84 | uriMappings = {}
85 | for doc in docs:
86 | urlParts = urllib.parse.urlparse(doc.uri)
87 | if urlParts.scheme != "file":
88 | # only download remote documents
89 | targetFileName = createUniqueFileName(targetDir, urlParts)
90 | uriMappings[doc.uri] = targetFileName
91 | downloadDoc(doc.uri, targetFileName)
92 | if uriMappings:
93 | createCatalog(uriMappings, createUniqueFileName(
94 | targetDir, urllib.parse.urlparse("catalog.xml")))
95 |
96 |
97 | def download_dts(dts, targetDir):
98 | if dts is None:
99 | print("Error executing script: dts must not be None!")
100 | else:
101 | download_docs(dts.documents, targetDir)
102 |
103 |
104 | def download_schema(schema, targetDir):
105 | if schema is None:
106 | print("Error executing script: schema must not be None!")
107 | else:
108 | download_docs(schema.documents, targetDir)
109 |
110 |
111 | def getTargetDir(job):
112 | return os.path.abspath(os.path.join(job.output_dir, job.script_params.get("target", "./output")))
113 |
114 |
115 | # Entry Points ###########################################################
116 |
117 | # Entry Point for valxsd (xsd)
118 | def on_xsd_finished(job, schema):
119 | download_schema(schema, getTargetDir(job))
120 |
121 |
122 | # Entry Point for valxml-withxsd (xsi)
123 | def on_xsi_finished(job, instance):
124 | if instance is None:
125 | print("Error executing script: instance must not be None!")
126 | else:
127 | download_schema(instance.schema, getTargetDir(job))
128 |
129 |
130 | # Entry Point for valxbrltaxonomy (dts)
131 | def on_dts_finished(job, dts):
132 | if dts is None:
133 | print("Error executing script: dts must not be None!")
134 | else:
135 | download_dts(dts, getTargetDir(job))
136 |
137 |
138 | # Entry Point for valxbrl (xbrl)
139 | def on_xbrl_finished(job, instance):
140 | if instance is None:
141 | print("Error executing script: instance must not be None!")
142 | else:
143 | download_dts(instance.dts, getTargetDir(job))
144 |
--------------------------------------------------------------------------------
/calculation_linkbase_traversal.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script uses RaptorXML Python API v2 to print out all the calculation networks found in the DTS as simple trees
18 | #
19 | # Example invocation:
20 | # raptorxmlxbrl valxbrl --script=calculation_linkbase_traversal.py
21 | # nanonull.xbrl
22 |
23 | from altova import *
24 |
25 |
26 | def concept_label(concept, label_role=None):
27 | if not label_role:
28 | label_role = xbrl.taxonomy.ROLE_LABEL
29 | # Find all labels matching the given criteria
30 | labels = list(concept.labels(label_role=label_role, lang='en'))
31 | if not labels:
32 | # If not labels are found fallback to concept QName
33 | return str(concept.qname)
34 | # Return text of first label found
35 | return labels[0].text
36 |
37 |
38 | def print_tree_level(network, concept, weight=None, level=1):
39 | # Print label of concept
40 | if weight:
41 | print('\t' * level, weight, '*', concept_label(concept))
42 | else:
43 | print('\t' * level, concept_label(concept))
44 |
45 | # Iterate over all child concepts
46 | for rel in network.relationships_from(concept):
47 | # Recurse for each child concept
48 | print_tree_level(network, rel.target, rel.weight, level + 1)
49 |
50 |
51 | def linkrole_definition(dts, linkrole):
52 | try:
53 | # Return the human readable roleType definition string for the given
54 | # linkrole if present
55 | return dts.role_type(linkrole).definition.value
56 | except:
57 | # Otherwise just return the linkrole URI
58 | return linkrole
59 |
60 |
61 | def print_calculation_tree(dts, linkrole):
62 | print(linkrole_definition(dts, linkrole))
63 |
64 | # Get the effective network of calculation relationships for the given
65 | # linkrole URI
66 | network = dts.calculation_base_set(linkrole).network_of_relationships()
67 |
68 | # Iterate over all root concepts
69 | for root in network.roots:
70 | print_tree_level(network, root)
71 |
72 |
73 | def print_calculation_linkbase(dts):
74 | # Iterate over all calculation extended link roles
75 | for linkrole in dts.calculation_link_roles():
76 | print_calculation_tree(dts, linkrole)
77 |
78 | # Main entry point, will be called by RaptorXML after the XBRL taxonomy
79 | # (DTS) validation job has finished
80 |
81 |
82 | def on_dts_finished(job, dts):
83 | # dts object will be None if validation was not successful
84 | if dts:
85 | print_calculation_linkbase(dts)
86 |
87 | # Main entry point, will be called by RaptorXML after the XBRL instance
88 | # validation job has finished
89 |
90 |
91 | def on_xbrl_finished(job, instance):
92 | # instance object will be None if validation was not successful
93 | if instance:
94 | print_calculation_linkbase(instance.dts)
95 |
--------------------------------------------------------------------------------
/csharp/CalculationLinkbaseTraversal/CalculationLinkbaseTraversal.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {5C17A904-F15C-4C73-83DA-18DD5AAFAE8C}
8 | Exe
9 | Properties
10 | CalculationLinkbaseTraversal
11 | CalculationLinkbaseTraversal
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/CalculationLinkbaseTraversal/CalculationLinkbaseTraversal.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CalculationLinkbaseTraversal", "CalculationLinkbaseTraversal.csproj", "{5C17A904-F15C-4C73-83DA-18DD5AAFAE8C}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {5C17A904-F15C-4C73-83DA-18DD5AAFAE8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {5C17A904-F15C-4C73-83DA-18DD5AAFAE8C}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {5C17A904-F15C-4C73-83DA-18DD5AAFAE8C}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {5C17A904-F15C-4C73-83DA-18DD5AAFAE8C}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/CalculationLinkbaseTraversal/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 | using Taxonomy = Altova.RaptorXml.Xbrl.Taxonomy;
21 |
22 | namespace CalculationLinkbaseTraversal
23 | {
24 | ///
25 | /// This example console application demonstrates how to load an XBRL instance, check for validation errors and traverse the calculation linkbase arcs.
26 | ///
27 | ///
28 | /// Given any XBRL instance, the calculation linkbase trees for each calculation linkrole are displayed.
29 | ///
30 | class Program
31 | {
32 | static string GetDefinition(Taxonomy.Dts dts, string roleUri)
33 | {
34 | var roleType = dts.GetRoleType(roleUri);
35 | if (roleType != null)
36 | {
37 | var definition = roleType.Definition;
38 | if (definition != null)
39 | return definition.Value;
40 | }
41 | return roleUri;
42 | }
43 |
44 | static string GetLabel(Taxonomy.Concept concept)
45 | {
46 | // Try to find a standard English label
47 | var labels = concept.GetLabels("http://www.xbrl.org/2003/role/label", null, "en");
48 | if (labels.Count > 0)
49 | return labels.First().Text;
50 |
51 | // Fallback to any other label that is assigned to the concept
52 | labels = concept.Labels;
53 | if (labels.Count > 0)
54 | return labels.First().Text;
55 |
56 | // If there are no labels, display the concept QName
57 | return concept.QName.ToString();
58 | }
59 |
60 | static void DisplayTreeNode(Taxonomy.CalculationRelationshipNetwork network, Taxonomy.Concept concept, decimal? weight = null, int level = 1)
61 | {
62 | if (weight == null)
63 | System.Console.WriteLine(String.Format("{0}{1}", new String(' ', level * 3), GetLabel(concept)));
64 | else
65 | System.Console.WriteLine(String.Format("{0}{1} * {2}", new String(' ', level * 3), weight, GetLabel(concept)));
66 | foreach (var rel in network.GetRelationshipsFrom(concept))
67 | {
68 | // Display the tree nodes recursively (DFS)
69 | DisplayTreeNode(network, rel.Target, rel.Weight, level + 1);
70 | }
71 | }
72 |
73 | static int Main(string[] args)
74 | {
75 | // Check if a command line argument was specified
76 | if (args.Length == 0)
77 | {
78 | System.Console.WriteLine("Please specify an XBRL instance file.");
79 | return 1;
80 | }
81 |
82 | // Load XBRL instance into memory
83 | Altova.RaptorXml.ErrorLog log;
84 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
85 |
86 | // Check for validation errors
87 | if (instance == null || log.HasErrors)
88 | {
89 | // Report validation errors
90 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.", args[0]));
91 | foreach (var error in log)
92 | {
93 | System.Console.WriteLine(error.Text);
94 | }
95 | return 1;
96 | }
97 |
98 | // Display the calculation tree for each linkrole
99 | foreach (var linkrole in instance.Dts.GetCalculationLinkRoles().OrderBy(x => GetDefinition(instance.Dts, x)))
100 | {
101 | System.Console.WriteLine(String.Format("{0} - {1}", GetDefinition(instance.Dts, linkrole), linkrole));
102 | var network = instance.Dts.GetCalculationNetwork(linkrole);
103 | foreach (var concept in network.Roots)
104 | {
105 | DisplayTreeNode(network, concept);
106 | }
107 | System.Console.WriteLine();
108 | }
109 |
110 | return 0;
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/csharp/DimensionalRelationshipSetTraversal/DimensionalRelationshipSetTraversal.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {4D793D89-6386-4A97-8C7D-149C3AB953A9}
8 | Exe
9 | Properties
10 | DimensionalRelationshipSetTraversal
11 | DimensionalRelationshipSetTraversal
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/DimensionalRelationshipSetTraversal/DimensionalRelationshipSetTraversal.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DimensionalRelationshipSetTraversal", "DimensionalRelationshipSetTraversal.csproj", "{4D793D89-6386-4A97-8C7D-149C3AB953A9}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {4D793D89-6386-4A97-8C7D-149C3AB953A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {4D793D89-6386-4A97-8C7D-149C3AB953A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {4D793D89-6386-4A97-8C7D-149C3AB953A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {4D793D89-6386-4A97-8C7D-149C3AB953A9}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/DimensionalRelationshipSetTraversal/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 | using Taxonomy = Altova.RaptorXml.Xbrl.Taxonomy;
21 | using Xdt = Altova.RaptorXml.Xbrl.Xdt;
22 |
23 | namespace DimensionalRelationshipSetTraversal
24 | {
25 | ///
26 | /// This example console application demonstrates how to load an XBRL instance, check for validation errors and traverse the dimensional relationship set.
27 | ///
28 | ///
29 | /// Given any XBRL instance, the dimensional relationship set for each linkrole are displayed.
30 | ///
31 | class Program
32 | {
33 | static string GetDefinition(Taxonomy.Dts dts, string roleUri)
34 | {
35 | var roleType = dts.GetRoleType(roleUri);
36 | if (roleType != null)
37 | {
38 | var definition = roleType.Definition;
39 | if (definition != null)
40 | return definition.Value;
41 | }
42 | return roleUri;
43 | }
44 |
45 | static string GetLabel(Taxonomy.Concept concept)
46 | {
47 | // Try to find a standard English label
48 | var labels = concept.GetLabels("http://www.xbrl.org/2003/role/label", null, "en");
49 | if (labels.Count > 0)
50 | return labels.First().Text;
51 |
52 | // Fallback to any other label that is assigned to the concept
53 | labels = concept.Labels;
54 | if (labels.Count > 0)
55 | return labels.First().Text;
56 |
57 | // If there are no labels, display the concept QName
58 | return concept.QName.ToString();
59 | }
60 |
61 | static void DisplayDomainMembers(Xdt.DRS drs, Taxonomy.Item item, string linkRole, int level = 1)
62 | {
63 | System.Console.WriteLine(String.Format("{0}{1}", new String(' ', level * 3), GetLabel(item)));
64 | foreach (var rel in drs.GetDomainMemberRelationships(item, linkRole))
65 | {
66 | DisplayDomainMembers(drs, rel.Target, rel.TargetRole ?? linkRole, level + 1);
67 | }
68 | }
69 |
70 | static void DisplayDimensions(Xdt.DRS drs, Xdt.Dimension dimension, string linkRole, int level = 1)
71 | {
72 | System.Console.WriteLine(String.Format("{0}{1}", new String(' ', level * 3), GetLabel(dimension)));
73 | foreach (var rel in drs.GetDimensionDomainRelationships(dimension, linkRole))
74 | {
75 | DisplayDomainMembers(drs, rel.Target, rel.TargetRole ?? linkRole, level + 1);
76 | }
77 | }
78 |
79 | static void DisplayHypercubes(Xdt.DRS drs, Xdt.Hypercube hypercube, string linkRole, int level = 1)
80 | {
81 | System.Console.WriteLine(String.Format("{0}{1}", new String(' ', level * 3), GetLabel(hypercube)));
82 | foreach (var rel in drs.GetHypercubeDimensionRelationships(hypercube, linkRole))
83 | {
84 | DisplayDimensions(drs, rel.Target, rel.TargetRole ?? linkRole, level + 1);
85 | }
86 | }
87 |
88 | static void DisplayPrimaryItems(Xdt.DRS drs, Taxonomy.Item item, string linkRole, int level = 1)
89 | {
90 | System.Console.WriteLine(String.Format("{0}{1}", new String(' ', level * 3), GetLabel(item)));
91 | foreach (var rel in drs.GetHashypercubeRelationships(item, linkRole))
92 | {
93 | DisplayHypercubes(drs, rel.Target, rel.TargetRole ?? linkRole, level + 1);
94 | }
95 | foreach (var rel in drs.GetDomainMemberRelationships(item, linkRole))
96 | {
97 | DisplayPrimaryItems(drs, rel.Target, rel.TargetRole ?? linkRole, level + 1);
98 | }
99 | }
100 |
101 | static int Main(string[] args)
102 | {
103 | // Check if a command line argument was specified
104 | if (args.Length == 0)
105 | {
106 | System.Console.WriteLine("Please specify an XBRL instance file.");
107 | return 1;
108 | }
109 |
110 | // Load XBRL instance into memory
111 | Altova.RaptorXml.ErrorLog log;
112 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
113 |
114 | // Check for validation errors
115 | if (instance == null || log.HasErrors)
116 | {
117 | // Report validation errors
118 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.", args[0]));
119 | foreach (var error in log)
120 | {
121 | System.Console.WriteLine(error.Text);
122 | }
123 | return 1;
124 | }
125 |
126 | // Display the dimensional relationship tree tree for each linkrole
127 | var drs = instance.Dts.DimensionalRelationshipSet;
128 | foreach (var linkRole in drs.LinkRoles)
129 | {
130 | System.Console.WriteLine(String.Format("{0} - {1}", GetDefinition(instance.Dts, linkRole), linkRole));
131 | foreach (var concept in drs.GetRoots(linkRole))
132 | {
133 | DisplayPrimaryItems(drs, concept, linkRole);
134 | }
135 | System.Console.WriteLine();
136 | }
137 |
138 | return 0;
139 | }
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/csharp/FindDuplicateContexts/FindDuplicateContexts.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {7BAB8C99-3282-452A-8F05-5DCA7D563C97}
8 | Exe
9 | Properties
10 | FindDuplicateContexts
11 | FindDuplicateContexts
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/FindDuplicateContexts/FindDuplicateContexts.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FindDuplicateContexts", "FindDuplicateContexts.csproj", "{7BAB8C99-3282-452A-8F05-5DCA7D563C97}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {7BAB8C99-3282-452A-8F05-5DCA7D563C97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {7BAB8C99-3282-452A-8F05-5DCA7D563C97}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {7BAB8C99-3282-452A-8F05-5DCA7D563C97}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {7BAB8C99-3282-452A-8F05-5DCA7D563C97}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/FindDuplicateContexts/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 |
21 | namespace FindDuplicateContexts
22 | {
23 | ///
24 | /// This example console application demonstrates how to load an XBRL instance, check for validation errors and search for duplicate contexts.
25 | ///
26 | ///
27 | /// Given any XBRL instance, all duplicate contexts are displayed.
28 | ///
29 | class Program
30 | {
31 | static int Main(string[] args)
32 | {
33 | // Check if a command line argument was specified
34 | if (args.Length == 0)
35 | {
36 | System.Console.WriteLine("Please specify an XBRL instance file.");
37 | return 1;
38 | }
39 |
40 | // Load XBRL instance into memory
41 | Altova.RaptorXml.ErrorLog log;
42 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
43 |
44 | // Check for validation errors
45 | if (instance == null || log.HasErrors)
46 | {
47 | // Report validation errors
48 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.", args[0]));
49 | foreach (var error in log)
50 | {
51 | System.Console.WriteLine(error.Text);
52 | }
53 | return 1;
54 | }
55 |
56 | // Find all duplicate contexts
57 | var contextDict = new Dictionary();
58 | foreach(var context in instance.Contexts)
59 | {
60 | var cs = new Xbrl.ConstraintSet(context);
61 | try
62 | {
63 | contextDict.Add(cs, context);
64 | }
65 | catch (ArgumentException)
66 | {
67 | System.Console.WriteLine(String.Format("Context {0} is a duplicate of context {1}.", context.Id, contextDict[cs].Id));
68 | }
69 | }
70 | System.Console.WriteLine();
71 |
72 | return 0;
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/csharp/FindDuplicateUnits/FindDuplicateUnits.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {9A6F509A-C3A0-46E5-9864-F28EBD99B0CD}
8 | Exe
9 | Properties
10 | FindDuplicateUnits
11 | FindDuplicateUnits
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/FindDuplicateUnits/FindDuplicateUnits.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FindDuplicateUnits", "FindDuplicateUnits.csproj", "{9A6F509A-C3A0-46E5-9864-F28EBD99B0CD}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {9A6F509A-C3A0-46E5-9864-F28EBD99B0CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {9A6F509A-C3A0-46E5-9864-F28EBD99B0CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {9A6F509A-C3A0-46E5-9864-F28EBD99B0CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {9A6F509A-C3A0-46E5-9864-F28EBD99B0CD}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/FindDuplicateUnits/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 |
21 | namespace FindDuplicateUnits
22 | {
23 | ///
24 | /// This example console application demonstrates how to load an XBRL instance, check for validation errors and search for duplicate units.
25 | ///
26 | ///
27 | /// Given any XBRL instance, all duplicate units are displayed.
28 | ///
29 | class Program
30 | {
31 | static int Main(string[] args)
32 | {
33 | // Check if a command line argument was specified
34 | if (args.Length == 0)
35 | {
36 | System.Console.WriteLine("Please specify an XBRL instance file.");
37 | return 1;
38 | }
39 |
40 | // Load XBRL instance into memory
41 | Altova.RaptorXml.ErrorLog log;
42 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
43 |
44 | // Check for validation errors
45 | if (instance == null || log.HasErrors)
46 | {
47 | // Report validation errors
48 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.", args[0]));
49 | foreach (var error in log)
50 | {
51 | System.Console.WriteLine(error.Text);
52 | }
53 | return 1;
54 | }
55 |
56 | // Find all duplicate units
57 | var unitDict = new Dictionary();
58 | foreach (var unit in instance.Units)
59 | {
60 | try
61 | {
62 | unitDict.Add(unit.AspectValue, unit);
63 | }
64 | catch (ArgumentException)
65 | {
66 | System.Console.WriteLine(String.Format("Unit {0} is a duplicate of unit {1}.", unit.Id, unitDict[unit.AspectValue].Id));
67 | }
68 | }
69 | System.Console.WriteLine();
70 |
71 | return 0;
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/csharp/FindFactsByName/FindFactsByName.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {6F2118D1-92A4-4A45-BD01-9DA8355A096E}
8 | Exe
9 | Properties
10 | FindFactsByName
11 | FindFactsByName
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/FindFactsByName/FindFactsByName.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FindFactsByName", "FindFactsByName.csproj", "{6F2118D1-92A4-4A45-BD01-9DA8355A096E}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {6F2118D1-92A4-4A45-BD01-9DA8355A096E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {6F2118D1-92A4-4A45-BD01-9DA8355A096E}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {6F2118D1-92A4-4A45-BD01-9DA8355A096E}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {6F2118D1-92A4-4A45-BD01-9DA8355A096E}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/FindFactsByName/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 | using Taxonomy = Altova.RaptorXml.Xbrl.Taxonomy;
21 |
22 | namespace FindFactsByName
23 | {
24 | ///
25 | /// This example console application demonstrates how to load an XBRL instance, check for validation errors and search for specific facts (by concept name).
26 | ///
27 | ///
28 | /// Given a SEC EDGAR filing, the values of all Assets facts are displayed.
29 | ///
30 | class Program
31 | {
32 | static Taxonomy.Concept GetAssetsConcept(Taxonomy.Dts dts)
33 | {
34 | // Find the us-gaap namespace referenced within the DTS
35 | string usgaap_namespace = null;
36 | foreach (var taxonomy in dts.TaxonomySchemas)
37 | {
38 | if (taxonomy.TargetNamespace.StartsWith("http://fasb.org/us-gaap/"))
39 | {
40 | usgaap_namespace = taxonomy.TargetNamespace;
41 | break;
42 | }
43 | }
44 | if (usgaap_namespace == null)
45 | return null;
46 |
47 | // Get the us-gaap:Assets concept wihtin the DTS
48 | return dts.ResolveConcept("Assets", usgaap_namespace);
49 | }
50 |
51 | static int Main(string[] args)
52 | {
53 | // Check if a command line argument was specified
54 | if (args.Length == 0)
55 | {
56 | System.Console.WriteLine("Please specify an XBRL instance file.");
57 | return 1;
58 | }
59 |
60 | // Load XBRL instance into memory
61 | Altova.RaptorXml.ErrorLog log;
62 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
63 |
64 | // Check for validation errors
65 | if (instance == null || log.HasErrors)
66 | {
67 | // Report validation errors
68 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.",args[0]));
69 | foreach (var error in log)
70 | {
71 | System.Console.WriteLine(error.Text);
72 | }
73 | return 1;
74 | }
75 |
76 | var concept = GetAssetsConcept(instance.Dts);
77 | if (concept == null)
78 | {
79 | System.Console.WriteLine("Taxonomy does not contain an Assets concept.");
80 | return 1;
81 | }
82 |
83 | // Find all US-GAAP Assets facts in the XBRL instance (filter instance facts by the concept aspect)
84 | var cs = new Xbrl.ConstraintSet();
85 | cs.Concept = new Xbrl.ConceptAspectValue(concept);
86 | var facts = instance.Facts.Filter(cs);
87 |
88 | System.Console.WriteLine(String.Format("Found {0} Assets facts.",facts.Count));
89 | foreach (Xbrl.Item fact in facts)
90 | {
91 | System.Console.WriteLine(String.Format("Assets fact in context {0} has the effective numeric value {1}.", fact.Context.Id, fact.EffectiveNumericValue));
92 | }
93 | System.Console.WriteLine();
94 |
95 | return 0;
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/csharp/FindFactsWithSameAspects/FindFactsWithSameAspects.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {29D0AE5E-6655-4B19-BBBB-D77A9C43BBA3}
8 | Exe
9 | Properties
10 | FindFactsWithSameAspects
11 | FindFactsWithSameAspects
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/FindFactsWithSameAspects/FindFactsWithSameAspects.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FindFactsWithSameAspects", "FindFactsWithSameAspects.csproj", "{29D0AE5E-6655-4B19-BBBB-D77A9C43BBA3}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {29D0AE5E-6655-4B19-BBBB-D77A9C43BBA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {29D0AE5E-6655-4B19-BBBB-D77A9C43BBA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {29D0AE5E-6655-4B19-BBBB-D77A9C43BBA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {29D0AE5E-6655-4B19-BBBB-D77A9C43BBA3}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/FindFactsWithSameAspects/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 | using Taxonomy = Altova.RaptorXml.Xbrl.Taxonomy;
21 |
22 | namespace FindFactsWithSameAspects
23 | {
24 | ///
25 | /// This example console application demonstrates how to load an XBRL instance, check for validation errors and search for specific facts (by concept name) that share the same aspects.
26 | ///
27 | ///
28 | /// Given a SEC EDGAR filing, the values of all paired Assets and LiabilitiesAndStockholdersEquity facts are displayed. This is similar to implicit filtering as defined by the Formula 1.0 specification.
29 | ///
30 | class Program
31 | {
32 | static Taxonomy.Concept GetUsGaapConcept(Taxonomy.Dts dts,string name)
33 | {
34 | // Find the us-gaap namespace referenced within the DTS
35 | string usgaap_namespace = null;
36 | foreach (var taxonomy in dts.TaxonomySchemas)
37 | {
38 | if (taxonomy.TargetNamespace.StartsWith("http://fasb.org/us-gaap/"))
39 | {
40 | usgaap_namespace = taxonomy.TargetNamespace;
41 | break;
42 | }
43 | }
44 | if (usgaap_namespace == null)
45 | return null;
46 |
47 | // Find the us-gaap concept wihtin the DTS
48 | return dts.ResolveConcept(name, usgaap_namespace);
49 | }
50 |
51 | static int Main(string[] args)
52 | {
53 | // Check if a command line argument was specified
54 | if (args.Length == 0)
55 | {
56 | System.Console.WriteLine("Please specify an XBRL instance file.");
57 | return 1;
58 | }
59 |
60 | // Load XBRL instance into memory
61 | Altova.RaptorXml.ErrorLog log;
62 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
63 |
64 | // Check for validation errors
65 | if (instance == null || log.HasErrors)
66 | {
67 | // Report validation errors
68 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.", args[0]));
69 | foreach (var error in log)
70 | {
71 | System.Console.WriteLine(error.Text);
72 | }
73 | return 1;
74 | }
75 |
76 | var assetsConcept = GetUsGaapConcept(instance.Dts,"Assets");
77 | if (assetsConcept == null)
78 | {
79 | System.Console.WriteLine("Taxonomy does not contain an Assets concept.");
80 | return 1;
81 | }
82 | var liabilitiesConcept = GetUsGaapConcept(instance.Dts, "LiabilitiesAndStockholdersEquity");
83 | if (liabilitiesConcept == null)
84 | {
85 | System.Console.WriteLine("Taxonomy does not contain an LiabilitiesAndStockholdersEquity concept.");
86 | return 1;
87 | }
88 |
89 | // Find all US-GAAP Assets facts in the XBRL instance (filter instance facts by the concept aspect)
90 | var cs = new Xbrl.ConstraintSet();
91 | cs.Concept = new Xbrl.ConceptAspectValue(assetsConcept);
92 | var assetsFacts = instance.Facts.Filter(cs);
93 |
94 | foreach (Xbrl.Item assetsFact in assetsFacts)
95 | {
96 | // Find all instance facts that share the same aspect values as the current assetsFact apart from the concept aspect.
97 | cs = new Xbrl.ConstraintSet(assetsFact);
98 | cs.Concept = new Xbrl.ConceptAspectValue(liabilitiesConcept);
99 | var liabilitiesFacts = instance.Facts.Filter(cs);
100 |
101 | foreach (Xbrl.Item liabilitiesFact in liabilitiesFacts)
102 | {
103 | System.Console.WriteLine(String.Format("Assets fact in context {0} has the effective numeric value {1}.", assetsFact.Context.Id, assetsFact.EffectiveNumericValue));
104 | System.Console.WriteLine(String.Format("LiabilitiesAndStockholdersEquity fact in context {0} has the effective numeric value {1}.", liabilitiesFact.Context.Id, liabilitiesFact.EffectiveNumericValue));
105 | System.Console.WriteLine();
106 | }
107 | }
108 |
109 | return 0;
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/csharp/InstanceStatistics/InstanceStatistics.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {71E1AA7F-D75D-4021-AE61-465CC319280D}
8 | Exe
9 | Properties
10 | InstanceStatistics
11 | InstanceStatistics
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/InstanceStatistics/InstanceStatistics.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InstanceStatistics", "InstanceStatistics.csproj", "{71E1AA7F-D75D-4021-AE61-465CC319280D}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {71E1AA7F-D75D-4021-AE61-465CC319280D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {71E1AA7F-D75D-4021-AE61-465CC319280D}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {71E1AA7F-D75D-4021-AE61-465CC319280D}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {71E1AA7F-D75D-4021-AE61-465CC319280D}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/InstanceStatistics/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 | using Taxonomy = Altova.RaptorXml.Xbrl.Taxonomy;
21 |
22 | namespace InstanceStatistics
23 | {
24 | ///
25 | /// This example console application demonstrates how to access the data model of the XBRL instance and the supporting DTS.
26 | ///
27 | ///
28 | /// Given any XBRL instance, some statistics about the XBRL instance the it's DTS are displayed.
29 | ///
30 | class Program
31 | {
32 | static void DisplayDtsStatistics(Taxonomy.Dts dts)
33 | {
34 | System.Console.WriteLine(String.Format("DTS contains {0} documents.", dts.Documents.Count));
35 | System.Console.WriteLine(String.Format("DTS contains {0} taxonomy schemas.", dts.TaxonomySchemas.Count));
36 | System.Console.WriteLine(String.Format("DTS contains {0} linkbases.", dts.Linkbases.Count));
37 | System.Console.WriteLine();
38 |
39 | System.Console.WriteLine(String.Format("DTS contains {0} concepts.", dts.Concepts.Count));
40 | System.Console.WriteLine(String.Format("DTS contains {0} tuples.", dts.Tuples.Count));
41 | System.Console.WriteLine(String.Format("DTS contains {0} non-xdt items.", dts.Items.Count - dts.Hypercubes.Count - dts.Dimensions.Count));
42 | System.Console.WriteLine(String.Format("DTS contains {0} hypercubes.", dts.Hypercubes.Count));
43 | System.Console.WriteLine(String.Format("DTS contains {0} dimensions.", dts.Dimensions.Count));
44 | System.Console.WriteLine();
45 |
46 | System.Console.WriteLine(String.Format("DTS contains {0} parameters.", dts.Parameters.Count));
47 | System.Console.WriteLine(String.Format("DTS contains {0} assertions.", dts.Assertions.Count));
48 | System.Console.WriteLine(String.Format("DTS contains {0} formulas.", dts.Formulas.Count));
49 | System.Console.WriteLine(String.Format("DTS contains {0} tables.", dts.Tables.Count));
50 | System.Console.WriteLine();
51 |
52 | System.Console.WriteLine(String.Format("DTS contains {0} definition linkroles.", dts.GetDefinitionLinkRoles().Count));
53 | System.Console.WriteLine(String.Format("DTS contains {0} presentation linkroles.", dts.GetPresentationLinkRoles().Count));
54 | System.Console.WriteLine(String.Format("DTS contains {0} calculation linkroles.", dts.GetCalculationLinkRoles().Count));
55 | System.Console.WriteLine(String.Format("DTS contains {0} label linkroles.", dts.GetLabelLinkRoles().Count));
56 | System.Console.WriteLine(String.Format("DTS contains {0} reference linkroles.", dts.GetReferenceLinkRoles().Count));
57 | System.Console.WriteLine();
58 | }
59 |
60 | static void DisplayInstanceStatistics(Xbrl.Instance instance)
61 | {
62 | System.Console.WriteLine(String.Format("Instance contains {0} contexts.", instance.Contexts.Count));
63 | System.Console.WriteLine(String.Format("Instance contains {0} instant period contexts.", instance.Contexts.Count(c => c.PeriodAspectValue.Type == Xbrl.PeriodType.Instant)));
64 | System.Console.WriteLine(String.Format("Instance contains {0} start/end period contexts.", instance.Contexts.Count(c => c.PeriodAspectValue.Type == Xbrl.PeriodType.StartEnd)));
65 | System.Console.WriteLine(String.Format("Instance contains {0} forever period contexts.", instance.Contexts.Count(c => c.PeriodAspectValue.Type == Xbrl.PeriodType.Forever)));
66 | System.Console.WriteLine();
67 |
68 | System.Console.WriteLine(String.Format("Instance contains {0} units.", instance.Units.Count));
69 | System.Console.WriteLine(String.Format("Instance contains {0} simple units.", instance.Units.Count(u => u.AspectValue.IsSimple)));
70 | System.Console.WriteLine(String.Format("Instance contains {0} currency units.", instance.Units.Count(u => u.AspectValue.IsMonetary)));
71 | System.Console.WriteLine();
72 |
73 | System.Console.WriteLine(String.Format("Instance contains {0} facts.", instance.Facts.Count));
74 | System.Console.WriteLine(String.Format("Instance contains {0} nil facts.", instance.NilFacts.Count));
75 | System.Console.WriteLine(String.Format("Instance contains {0} top-level item facts.", instance.ChildItems.Count));
76 | System.Console.WriteLine(String.Format("Instance contains {0} top-level tuple facts.", instance.ChildTuples.Count));
77 | System.Console.WriteLine();
78 |
79 | var footnoteCounts = new Dictionary();
80 | foreach (var footnoteLink in instance.FootnoteLinks)
81 | {
82 | foreach (var footnote in footnoteLink.Resources.OfType())
83 | {
84 | int count;
85 | footnoteCounts.TryGetValue(footnote.XmlLang, out count);
86 | footnoteCounts[footnote.XmlLang] = count + 1;
87 | }
88 | }
89 | if (footnoteCounts.Count > 0)
90 | {
91 | foreach (var lang in footnoteCounts)
92 | {
93 | System.Console.WriteLine(String.Format("Instance contains {0} footnote resources in language {1}.", lang.Value, lang.Key));
94 | }
95 | }
96 | else
97 | {
98 | System.Console.WriteLine("Instance does not contain any footnote resources.");
99 | }
100 | System.Console.WriteLine();
101 | }
102 |
103 | static int Main(string[] args)
104 | {
105 | // Check if a command line argument was specified
106 | if (args.Length == 0)
107 | {
108 | System.Console.WriteLine("Please specify an XBRL instance file.");
109 | return 1;
110 | }
111 |
112 | // Load XBRL instance into memory
113 | Altova.RaptorXml.ErrorLog log;
114 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
115 |
116 | // Check for validation errors
117 | if (instance == null || log.HasErrors)
118 | {
119 | // Report validation errors
120 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.", args[0]));
121 | foreach (var error in log)
122 | {
123 | System.Console.WriteLine(error.Text);
124 | }
125 | return 1;
126 | }
127 |
128 | // Display some statistics about the XBRL instance and it's DTS
129 | DisplayDtsStatistics(instance.Dts);
130 | DisplayInstanceStatistics(instance);
131 |
132 | return 0;
133 | }
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/csharp/OIMReportBuilderExample/OIMReportBuilderExample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {C93D10B5-A30E-465C-ACB8-C28BDA53BBD4}
8 | Exe
9 | OIMReportBuilderExample
10 | OIMReportBuilderExample
11 | v4.8
12 | 512
13 | true
14 | true
15 |
16 |
17 | true
18 | bin\x64\Debug\
19 | DEBUG;TRACE
20 | full
21 | x64
22 | 7.3
23 | prompt
24 | true
25 |
26 |
27 | bin\x64\Release\
28 | TRACE
29 | true
30 | pdbonly
31 | x64
32 | 7.3
33 | prompt
34 | true
35 |
36 |
37 |
38 | False
39 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/csharp/OIMReportBuilderExample/OIMReportBuilderExample.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.12.35527.113
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OIMReportBuilderExample", "OIMReportBuilderExample.csproj", "{C93D10B5-A30E-465C-ACB8-C28BDA53BBD4}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|x64 = Debug|x64
11 | Release|x64 = Release|x64
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {C93D10B5-A30E-465C-ACB8-C28BDA53BBD4}.Debug|x64.ActiveCfg = Debug|x64
15 | {C93D10B5-A30E-465C-ACB8-C28BDA53BBD4}.Debug|x64.Build.0 = Debug|x64
16 | {C93D10B5-A30E-465C-ACB8-C28BDA53BBD4}.Release|x64.ActiveCfg = Release|x64
17 | {C93D10B5-A30E-465C-ACB8-C28BDA53BBD4}.Release|x64.Build.0 = Release|x64
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/PresentationLinkbaseTraversal/PresentationLinkbaseTraversal.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {025C0AC7-4D92-4253-A5CB-FFBE5B292A26}
8 | Exe
9 | Properties
10 | PresentationLinkbaseTraversal
11 | PresentationLinkbaseTraversal
12 | v4.0
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
58 |
--------------------------------------------------------------------------------
/csharp/PresentationLinkbaseTraversal/PresentationLinkbaseTraversal.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.40629.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PresentationLinkbaseTraversal", "PresentationLinkbaseTraversal.csproj", "{025C0AC7-4D92-4253-A5CB-FFBE5B292A26}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {025C0AC7-4D92-4253-A5CB-FFBE5B292A26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {025C0AC7-4D92-4253-A5CB-FFBE5B292A26}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {025C0AC7-4D92-4253-A5CB-FFBE5B292A26}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {025C0AC7-4D92-4253-A5CB-FFBE5B292A26}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/csharp/PresentationLinkbaseTraversal/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using Xbrl = Altova.RaptorXml.Xbrl;
20 | using Taxonomy = Altova.RaptorXml.Xbrl.Taxonomy;
21 |
22 | namespace PresentationLinkbaseTraversal
23 | {
24 | ///
25 | /// This example console application demonstrates how to load an XBRL instance, check for validation errors and traverse the presentation linkbase arcs.
26 | ///
27 | ///
28 | /// Given any XBRL instance, the presentation linkbase trees for each presentation linkrole are displayed.
29 | ///
30 | class Program
31 | {
32 | static string GetDefinition(Taxonomy.Dts dts, string roleUri)
33 | {
34 | var roleType = dts.GetRoleType(roleUri);
35 | if (roleType != null)
36 | {
37 | var definition = roleType.Definition;
38 | if (definition != null)
39 | return definition.Value;
40 | }
41 | return roleUri;
42 | }
43 |
44 | static string GetLabel(Taxonomy.Concept concept, string labelRole)
45 | {
46 | Taxonomy.LabelCollection labels;
47 |
48 | // Try to find a English label with the given labelRole
49 | if (labelRole != null)
50 | {
51 | labels = concept.GetLabels(labelRole, null, "en");
52 | if (labels.Count > 0)
53 | return labels.First().Text;
54 | }
55 |
56 | // Try to find a standard English label
57 | labels = concept.GetLabels("http://www.xbrl.org/2003/role/label", null, "en");
58 | if (labels.Count > 0)
59 | return labels.First().Text;
60 |
61 | // Fallback to any other label that is assigned to the concept
62 | labels = concept.Labels;
63 | if (labels.Count > 0)
64 | return labels.First().Text;
65 |
66 | // If there are no labels, display the concept QName
67 | return concept.QName.ToString();
68 | }
69 |
70 | static void DisplayTreeNode(Taxonomy.PresentationRelationshipNetwork network, Taxonomy.Concept concept, string preferredLabelRole = null, int level = 1)
71 | {
72 | System.Console.WriteLine(String.Format("{0}{1}", new String(' ', level*3), GetLabel(concept, preferredLabelRole)));
73 | foreach (var rel in network.GetRelationshipsFrom(concept))
74 | {
75 | // Display the tree nodes recursively (DFS)
76 | DisplayTreeNode(network, rel.Target, rel.PreferredLabel, level + 1);
77 | }
78 | }
79 |
80 | static int Main(string[] args)
81 | {
82 | // Check if a command line argument was specified
83 | if (args.Length == 0)
84 | {
85 | System.Console.WriteLine("Please specify an XBRL instance file.");
86 | return 1;
87 | }
88 |
89 | // Load XBRL instance into memory
90 | Altova.RaptorXml.ErrorLog log;
91 | var instance = Xbrl.Instance.CreateFromUrl(args[0], out log);
92 |
93 | // Check for validation errors
94 | if (instance == null || log.HasErrors)
95 | {
96 | // Report validation errors
97 | System.Console.WriteLine(String.Format("Failed to load XBRL instance file {0}.", args[0]));
98 | foreach (var error in log)
99 | {
100 | System.Console.WriteLine(error.Text);
101 | }
102 | return 1;
103 | }
104 |
105 | // Display the presentation tree for each linkrole
106 | foreach (var linkrole in instance.Dts.GetPresentationLinkRoles().OrderBy(x => GetDefinition(instance.Dts, x)))
107 | {
108 | System.Console.WriteLine(String.Format("{0} - {1}", GetDefinition(instance.Dts, linkrole), linkrole));
109 | var network = instance.Dts.GetPresentationNetwork(linkrole);
110 | foreach (var concept in network.Roots)
111 | {
112 | DisplayTreeNode(network, concept);
113 | }
114 | System.Console.WriteLine();
115 | }
116 |
117 | return 0;
118 | }
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/csharp/README.md:
--------------------------------------------------------------------------------
1 | # RaptorXML-Examples in C# #
2 |
3 | Examples for using the [C# API](http://manual.altova.com/RaptorXML/dotnetapiv2/html/) of [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html).
4 |
5 | #### Load-Validate
6 | These example console applications show how to load an XBRL instance, check for validation errors and perform one small additional feature for demonstration purposes.
7 |
8 | ##### XBRLTablesToExcel
9 | * an example demonstrating how to load XBRL instances, process the table linkbase and convert XBRL tables to Excel tables. This example can also transform EBA and EIOPA instances to Excel workbooks.
10 |
11 | ##### XBRLImportTest
12 | * a very simple and minimalistic example demonstrating how to load XBRL instances and insert fact information into a single large DB table
13 |
14 | ##### CalculationLinkbaseTraversal
15 | * traverse the calculation linkbase arcs
16 |
17 | ##### DimensionalRelationshipSetTraversal
18 | * traverse the dimensional relationship set
19 |
20 | ##### FindDuplicateContexts
21 | * search for duplicate contexts
22 |
23 | ##### FindDuplicateUnits
24 | * search for duplicate units
25 |
26 | ##### FindFactsByName
27 | * search for specific facts (by concept name)
28 |
29 | ##### FindFactsWithSameAspects
30 | * search for specific facts (by concept name) that share the same aspects
31 |
32 | ##### InstanceStatistics
33 | * access the data model of the XBRL instance and the supporting DTS
34 |
35 | ##### PresentationLinkbaseTraversal
36 | * traverse the presentation linkbase arcs
37 |
38 | ##### XPathXQueryXslt
39 | * Introductory examples for the XPath, XQuery and XSLT engine usage via the C# API
40 |
--------------------------------------------------------------------------------
/csharp/XBRLImportTest/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/csharp/XBRLImportTest/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Data.OleDb;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Altova.RaptorXml;
8 | using Xbrl = Altova.RaptorXml.Xbrl;
9 |
10 | namespace XBRLImportTest
11 | {
12 | // A very simple and minimalistic example demonstrating how to load XBRL instances and insert fact information into a single large DB table.
13 | class Program
14 | {
15 | //CREATE TABLE
16 | // [Facts] (
17 | // [instance_url] TEXT (255) NOT NULL,
18 | // [concept_name] TEXT (255) NOT NULL,
19 | // [concept_namespace] TEXT (255) NOT NULL,
20 | // [entity_identifier] TEXT (255) NOT NULL,
21 | // [period_start] DATETIME NULL,
22 | // [period_end] DATETIME NULL,
23 | // [strval] MEMO NULL,
24 | // [numval] NUMERIC (28, 5) NULL,
25 | // [currency] TEXT (255) NULL) ;
26 |
27 | static String CONNECTION_STRING = "Provider=Microsoft.ACE.OLEDB.12.0; Data source={0}";
28 | static String INSERT_QUERY = "INSERT INTO Facts VALUES(@url, @name, @ns, @identifier, @start, @end, @strval, @numval, @currency)";
29 |
30 | static void Main(string[] args)
31 | {
32 | if (args.Length != 1)
33 | {
34 | Console.WriteLine("Usage: XBRLImportTest instance.xbrl");
35 | return;
36 | }
37 | string url = args[0]; // @"C:\Temp\msft-20170930\msft-20170930.xml";
38 |
39 | System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
40 | conn.ConnectionString = String.Format(CONNECTION_STRING, @"xbrl.accdb");
41 |
42 | try
43 | {
44 | // Open DB connection
45 | conn.Open();
46 |
47 |
48 | // Load XBRL instance
49 | var settings = new Xbrl.InstanceSettings();
50 |
51 | // Custom catalogs or taxonomy packages
52 | //settings.CatalogUrls.Add(@"mycatalog.xml");
53 | //settings.TaxonomyPackageUrls.Add(@"mytaxonomypkg.zip");
54 |
55 | // In case of fixed taxonomy entrypoints, preload the DTS to increase the performance when bulk importing multiple instances
56 | // settings.DTS = Xbrl.Taxonomy.Dts.CreateFromUrl(@"entrypoint.xsd", out log);
57 |
58 | ErrorLog log;
59 | var inst = Xbrl.Instance.CreateFromUrl(url, settings, out log);
60 | if (log.HasErrors)
61 | throw new Exception(log.Text);
62 |
63 | // Insert each fact into DB (assuming instance does not contain tuples)
64 | foreach (Xbrl.Item fact in inst.Facts)
65 | {
66 | // Access fact and aspect values
67 | var name = fact.QName.LocalName;
68 | var ns = fact.QName.NamespaceName;
69 |
70 | var identifier = fact.EntityIdentifierAspectValue.Identifier;
71 |
72 | DateTime? period_start = null;
73 | DateTime? period_end = null;
74 | var period = fact.PeriodAspectValue;
75 | switch(period.Type)
76 | {
77 | case Xbrl.PeriodType.Instant:
78 | period_start = period.Instant;
79 | break;
80 | case Xbrl.PeriodType.StartEnd:
81 | period_start = period.Start;
82 | period_end = period.End;
83 | break;
84 | case Xbrl.PeriodType.Forever:
85 | break;
86 | }
87 |
88 | var strval = fact.NormalizedValue;
89 |
90 | decimal? numval = null;
91 | string currency = null;
92 | if (fact.Concept.IsNumeric)
93 | {
94 | // Use EffectiveNumericValue to get XBRL rounded value taking into account @decimals/@precision
95 | numval = fact.NumericValue;
96 | var unit = fact.UnitAspectValue;
97 | if (unit.IsMonetary)
98 | currency = unit.Iso4217Currency;
99 | }
100 |
101 | // Insert fact row
102 | OleDbCommand cmd = new OleDbCommand(INSERT_QUERY, conn);
103 | cmd.Parameters.Add("@url", OleDbType.VarChar).Value = url;
104 | cmd.Parameters.Add("@name", OleDbType.VarChar).Value = name;
105 | cmd.Parameters.Add("@ns", OleDbType.VarChar).Value = ns;
106 | cmd.Parameters.Add("@identifier", OleDbType.VarChar).Value = identifier;
107 | cmd.Parameters.Add("@start", OleDbType.DBTimeStamp).Value = (object)period_start ?? DBNull.Value;
108 | cmd.Parameters.Add("@end", OleDbType.DBTimeStamp).Value = (object)period_end ?? DBNull.Value;
109 | cmd.Parameters.Add("@strval", OleDbType.LongVarChar).Value = (object)strval ?? DBNull.Value;
110 | cmd.Parameters.Add("@numval", OleDbType.Numeric).Value = (object)numval ?? DBNull.Value;
111 | cmd.Parameters.Add("@currency", OleDbType.VarChar).Value = (object)currency ?? DBNull.Value;
112 | cmd.ExecuteNonQuery();
113 | }
114 |
115 |
116 | Console.WriteLine(String.Format("Imported XBRL instance '{0}' successfully!", url));
117 | }
118 | catch (Exception ex)
119 | {
120 | Console.WriteLine("Failed: " + ex.Message);
121 | }
122 | finally
123 | {
124 | conn.Close();
125 | }
126 | }
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/csharp/XBRLImportTest/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("XBRLImportTest")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("XBRLImportTest")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("e44a1a85-3ed6-4c6c-b83c-50f384fd5cf3")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/csharp/XBRLImportTest/XBRLImportTest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}
8 | Exe
9 | XBRLImportTest
10 | XBRLImportTest
11 | v4.6.1
12 | 512
13 | true
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 | true
36 | bin\x86\Debug\
37 | DEBUG;TRACE
38 | full
39 | x86
40 | prompt
41 | MinimumRecommendedRules.ruleset
42 | true
43 |
44 |
45 | bin\x86\Release\
46 | TRACE
47 | true
48 | pdbonly
49 | x86
50 | prompt
51 | MinimumRecommendedRules.ruleset
52 | true
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/csharp/XBRLImportTest/XBRLImportTest.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27703.2000
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XBRLImportTest", "XBRLImportTest.csproj", "{E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Debug|x86 = Debug|x86
12 | Release|Any CPU = Release|Any CPU
13 | Release|x86 = Release|x86
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Debug|x86.ActiveCfg = Debug|x86
19 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Debug|x86.Build.0 = Debug|x86
20 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Release|x86.ActiveCfg = Release|x86
23 | {E44A1A85-3ED6-4C6C-B83C-50F384FD5CF3}.Release|x86.Build.0 = Release|x86
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {1D8C7AAC-016C-4DAD-8FF4-2C9725BC7009}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/DefaultTableStyle.cs:
--------------------------------------------------------------------------------
1 | using ClosedXML.Excel;
2 |
3 | namespace XbrlTablesToExcel
4 | {
5 | class DefaultTableStyle : ITableStyle
6 | {
7 | public IXLRange ApplyTOCFormat(IXLRange range, int depth, bool isTable, bool isReported)
8 | {
9 | range.DataType = XLDataType.Text;
10 | if (isTable)
11 | {
12 | if (isReported)
13 | {
14 | range.Style.Font.Bold = depth == 0;
15 | range.Style.Font.Underline = XLFontUnderlineValues.Single;
16 | }
17 | else
18 | {
19 | range.Style.Font.FontColor = XLColor.LightGray;
20 | }
21 | }
22 | else
23 | {
24 | range.Style.Font.Bold = depth == 0;
25 | range.Style.Font.Underline = XLFontUnderlineValues.Single;
26 | }
27 | range.Style.NumberFormat.NumberFormatId = 49; // @
28 | return range;
29 | }
30 |
31 | public IXLRange ApplyTitleFormat(IXLRange range)
32 | {
33 | if (range.ColumnCount() > 1)
34 | range.Merge();
35 | range.Style.Alignment.WrapText = true;
36 | range.Style.Border.OutsideBorder = XLBorderStyleValues.None;
37 | range.Style.Fill.BackgroundColor = XLColor.FromTheme(XLThemeColor.Accent1);
38 | range.Style.Font.FontColor = XLColor.FromTheme(XLThemeColor.Text1);
39 | range.Style.Font.Bold = true;
40 | range.Style.NumberFormat.NumberFormatId = 49; // @
41 | range.DataType = XLDataType.Text;
42 | return range;
43 | }
44 | public IXLRange ApplyTitleHeaderFormat(IXLRange range)
45 | {
46 | range.Merge();
47 | range.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
48 | range.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
49 | range.Style.Alignment.WrapText = true;
50 | range.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
51 | range.Style.Fill.BackgroundColor = XLColor.FromTheme(XLThemeColor.Background2);
52 | range.Style.Font.Bold = true;
53 | range.Style.Font.FontColor = XLColor.FromTheme(XLThemeColor.Text1);
54 | range.Style.NumberFormat.NumberFormatId = 49; // @
55 | range.DataType = XLDataType.Text;
56 | return range;
57 | }
58 | public IXLRange ApplyHeaderFormat(IXLRange range, HeaderType axis, bool bIsOpenAspect = false)
59 | {
60 | if (range.ColumnCount() > 1 || range.RowCount() > 1)
61 | range.Merge();
62 |
63 | if (axis == HeaderType.XAxis && range.ColumnCount() > 1)
64 | range.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
65 | else if (axis == HeaderType.YAxis && range.RowCount() > 1)
66 | range.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
67 | range.Style.Alignment.WrapText = axis != HeaderType.YAxis;
68 | range.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
69 | range.Style.Fill.BackgroundColor = bIsOpenAspect ? XLColor.FromTheme(XLThemeColor.Background2, 0.4) : XLColor.FromTheme(XLThemeColor.Background2);
70 | range.Style.Font.FontColor = XLColor.FromTheme(XLThemeColor.Text1);
71 | range.Style.NumberFormat.NumberFormatId = 49; // @
72 | range.DataType = XLDataType.Text;
73 | return range;
74 | }
75 | public IXLRange ApplyHeaderRcCodeFormat(IXLRange range, HeaderType axis, bool bIsOpenAspect = false)
76 | {
77 | range.DataType = XLDataType.Text;
78 | range.Style.Alignment.WrapText = true;
79 | range.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
80 | range.Style.Fill.BackgroundColor = XLColor.FromTheme(XLThemeColor.Background2, -0.2);
81 | range.Style.Font.FontColor = XLColor.FromTheme(XLThemeColor.Text1);
82 | range.Style.NumberFormat.NumberFormatId = 49; // @
83 | range.DataType = XLDataType.Text;
84 | return range;
85 | }
86 | public IXLRange ApplyDataCellFormat(IXLRange range, DataCellType type)
87 | {
88 | //range.Style.Fill.BackgroundColor = XLColor.FromTheme(XLThemeColor.Background1);
89 | switch (type)
90 | {
91 | case DataCellType.Boolean:
92 | range.DataType = XLDataType.Boolean;
93 | break;
94 | case DataCellType.Percentage:
95 | range.DataType = XLDataType.Number;
96 | range.Style.NumberFormat.NumberFormatId = 9; // 0%
97 | break;
98 | case DataCellType.Integer:
99 | range.DataType = XLDataType.Number;
100 | range.Style.NumberFormat.NumberFormatId = 1; // 0
101 | break;
102 | case DataCellType.Decimal:
103 | range.DataType = XLDataType.Number;
104 | range.Style.NumberFormat.Format = "#,##0.######";
105 | break;
106 | case DataCellType.Monetary:
107 | range.DataType = XLDataType.Number;
108 | range.Style.NumberFormat.NumberFormatId = 4; // #,##0.00
109 | break;
110 | case DataCellType.Date:
111 | range.DataType = XLDataType.DateTime;
112 | range.Style.NumberFormat.NumberFormatId = 14; // d/m/yyyy
113 | break;
114 | case DataCellType.DateTime:
115 | range.DataType = XLDataType.DateTime;
116 | range.Style.NumberFormat.NumberFormatId = 22; // m/d/yyyy H:mm
117 | break;
118 | case DataCellType.Label:
119 | range.DataType = XLDataType.Text;
120 | range.Style.Alignment.WrapText = true;
121 | range.Style.NumberFormat.NumberFormatId = 49; // @
122 | break;
123 | case DataCellType.Text:
124 | range.DataType = XLDataType.Text;
125 | range.Style.Alignment.WrapText = true;
126 | range.Style.NumberFormat.NumberFormatId = 49; // @
127 | break;
128 | }
129 | return range;
130 | }
131 | public IXLRange ApplyDataEmptyCellFormat(IXLRange range)
132 | {
133 | //range.Style.Fill.BackgroundColor = XLColor.FromTheme(XLThemeColor.Background1);
134 | return range;
135 | }
136 | public IXLRange ApplyDataInvalidCellFormat(IXLRange range)
137 | {
138 | range.Style.Border.DiagonalBorder = XLBorderStyleValues.Thin;
139 | range.Style.Border.DiagonalUp = true;
140 | range.Style.Border.DiagonalDown = true;
141 | range.Style.Fill.BackgroundColor = XLColor.FromTheme(XLThemeColor.Text2);
142 | return range;
143 | }
144 | public IXLTable ApplyTableFormat(IXLTable table)
145 | {
146 | table.Theme = XLTableTheme.None;
147 | table.DataRange.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
148 | return table;
149 | }
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/ITableStyle.cs:
--------------------------------------------------------------------------------
1 | using ClosedXML.Excel;
2 |
3 | namespace XbrlTablesToExcel
4 | {
5 | enum HeaderType
6 | {
7 | XAxis,
8 | YAxis,
9 | ZAxis,
10 | Other
11 | }
12 | enum DataCellType
13 | {
14 | Boolean,
15 | Integer,
16 | Decimal,
17 | Percentage,
18 | Monetary,
19 | Date,
20 | DateTime,
21 | Label,
22 | QName,
23 | Text
24 | }
25 |
26 | interface ITableStyle
27 | {
28 | IXLRange ApplyTOCFormat(IXLRange range, int depth, bool isTable, bool isReported);
29 | IXLRange ApplyTitleFormat(IXLRange range);
30 | IXLRange ApplyTitleHeaderFormat(IXLRange range);
31 | IXLRange ApplyHeaderFormat(IXLRange range, HeaderType axis, bool bIsOpenAspect = false);
32 | IXLRange ApplyHeaderRcCodeFormat(IXLRange range, HeaderType axis, bool bIsOpenAspect = false);
33 | IXLRange ApplyDataCellFormat(IXLRange range, DataCellType type);
34 | IXLRange ApplyDataEmptyCellFormat(IXLRange range);
35 | IXLRange ApplyDataInvalidCellFormat(IXLRange range);
36 | IXLTable ApplyTableFormat(IXLTable table);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("XBRL Tables to Excel Converter")]
9 | [assembly: AssemblyDescription("Converts XBRL table linkbase tables to Excel tables. Uses the Altova RaptorXML+XBRL .NET API to process XBRL instance files. Writes Excel workbooks using ClosedXML.")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Altova GmbH")]
12 | [assembly: AssemblyProduct("XBRLTablesToExcel")]
13 | [assembly: AssemblyCopyright("Copyright © Altova GmbH 2019")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("d95fa9ba-8cd4-4c0e-9021-c150a8607808")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/README.md:
--------------------------------------------------------------------------------
1 | # XBRLTablesToExcel C# example
2 |
3 | The following example demonstrats how to load an XBRL instance, process the table linkbase and convert XBRL tables to Excel tables. This example can also transform EBA and EIOPA instances to Excel workbooks.
4 | The example is using the [C# API](http://manual.altova.com/RaptorXML/dotnetapiv2/html/) of [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html) engine to process XBRL files and [ClosedXML](https://github.com/ClosedXML/ClosedXML) to generate Excel workbooks. A Microsoft Office installation is not required for the generation of the Excel report.
5 |
6 |
7 | ##### Prerequisits
8 | * Visual Studio 2017 Community edition or higher
9 | * Altova [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html) 2020 64-bit version
10 |
11 | ##### Compilation
12 | * Open the solution in Visual Studio
13 | * Install/Restore missing NuGet package references
14 | * Either make sure the Package Restore options in Tools|Options|NuGet Package Manager are enabled
15 | * Or right click on the XbrlTablesToExcel project and select Manage NuGet Packages, then click on Restore packages at the top of the page
16 | * For additional information see [Troubleshooting package restore errors](https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore-troubleshooting)
17 | * If Altova [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html) 2020 was not installed in the default location `C:\Program Files\Altova\RaptorXMLXBRLServer2020\`
18 | * Delete the existing reference to raptorxmlxbrlapi and add a new reference by browsing to `raptorxmlxbrlapi.dll`
19 | * Build the solution
20 |
21 | ##### Customizations
22 | * You can easily change the table styles by modifying the code in the DefaultTableStyle.cs file
23 |
24 | ##### Example usage
25 | * Generate an Excel report from an EBA/EIOPA XBRL instance
26 |
27 | XBRLTablesToExcel in.xbrl out.xlsx
28 |
29 | * To list the available options
30 |
31 | XBRLTablesToExcel --help
32 |
33 | * To enable additional debug output
34 |
35 | XBRLTablesToExcel in.xbrl out.xlsx --log verbose.log
36 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/Report.cs:
--------------------------------------------------------------------------------
1 | using Altova.RaptorXml;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using Xbrl = Altova.RaptorXml.Xbrl;
6 | using Oim = Altova.RaptorXml.Oim;
7 |
8 | namespace XbrlTablesToExcel
9 | {
10 | public class Report
11 | {
12 | private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
13 |
14 | public string Url { get { return Instance.Uri; } }
15 | public Xbrl.Instance Instance { get; private set; }
16 | public Xbrl.Taxonomy.Dts Dts { get { return Instance.Dts; } }
17 | public Xbrl.Table.Layout.TableModel TableModel { get; private set; }
18 | public Xbrl.Context ReportingContext { get; private set; }
19 | public string ReportingCurrency { get; private set; }
20 | public string ReportingEntityIdentifier { get { return ReportingContext?.Entity.Identifier.Value; } }
21 | public string ReportingEntityScheme { get { return ReportingContext?.Entity.Identifier.Scheme; } }
22 | public DateTime? ReferenceDate
23 | {
24 | get
25 | {
26 | var period = ReportingContext?.Period;
27 | if (period?.Instant != null)
28 | return period.Instant.Value.AddDays(-1);
29 | else if (period?.EndDate != null)
30 | return period.EndDate.Value.AddDays(-1);
31 | return null;
32 | }
33 | }
34 | public string EntryPointName
35 | {
36 | get
37 | {
38 | var dts = this.Instance.Dts;
39 | var moduleType = dts.Schema.ResolveTypeDefinition("moduleType", "http://www.eurofiling.info/xbrl/ext/model");
40 | if (moduleType != null)
41 | {
42 | var moduleItem = dts.GetItemsByType(moduleType, false).FirstOrDefault();
43 | if (moduleItem != null)
44 | return XbrlUtils.GetLabel(moduleItem);
45 | }
46 | return null;
47 | }
48 | }
49 | public string EntryPointUrl { get { return this.Instance.SchemaRefs.First().XlinkHref; } }
50 | public Dictionary FilingIndicators { get; private set; }
51 |
52 | public bool GetFilingIndicator(string filingIndicator)
53 | {
54 | if (FilingIndicators.Count == 0)
55 | return true;
56 | if (FilingIndicators.TryGetValue(filingIndicator, out bool value))
57 | return value;
58 | return false;
59 | }
60 |
61 | public Report(string url, Xbrl.Taxonomy.Dts dts=null)
62 | {
63 | Logger.Debug("Loading XBRL instance {0}", url);
64 | ErrorLog errorLog = null;
65 | Oim.OIM oim = null;
66 |
67 | // Detect the document type of the XBRL instance (xBRL-XML, xBRL-JSON, xBRL-CSV)
68 | string docType = Oim.OIM.DetectDocumentType(url);
69 | switch (docType)
70 | {
71 | case "https://xbrl.org/2021/xbrl-csv":
72 | oim = Oim.OIM.CreateFromCSV(url, out errorLog);
73 | if (oim == null || errorLog.HasErrors)
74 | throw new ApplicationException(errorLog.ToString());
75 | break;
76 | case "https://xbrl.org/2021/xbrl-json":
77 | oim = Oim.OIM.CreateFromJSON(url, out errorLog);
78 | if (oim == null || errorLog.HasErrors)
79 | throw new ApplicationException(errorLog.ToString());
80 | break;
81 | case "https://xbrl.org/2021/xbrl-xml":
82 | // will be loaded later
83 | break;
84 | default:
85 | throw new ApplicationException(String.Format("Unexpected document type: {0}", docType));
86 | }
87 |
88 | Xbrl.Instance instance = null;
89 | if (oim != null)
90 | {
91 | // convert xBRL-CSV and xBRL-JSON reports to xBRL-XML
92 | var xmlDoc = oim.ToXML(out errorLog);
93 | if (errorLog.HasErrors)
94 | throw new ApplicationException(errorLog.ToString());
95 |
96 | instance = Xbrl.Instance.CreateFromElement(xmlDoc.DocumentElement, out errorLog);
97 | }
98 | else
99 | {
100 | instance = Xbrl.Instance.CreateFromUrl(url, XbrlUtils.GetCreateInstanceOptions(dts), out errorLog);
101 | }
102 |
103 | if (instance == null || errorLog.HasErrors)
104 | throw new ApplicationException(errorLog.ToString());
105 |
106 | Init(instance);
107 | }
108 | public Report(Xbrl.Instance instance)
109 | {
110 | Init(instance);
111 | }
112 |
113 | public TableTree GetTableTree()
114 | {
115 | return new TableTree(this);
116 | }
117 |
118 | void Init(Xbrl.Instance instance)
119 | {
120 | this.Instance = instance;
121 |
122 | Logger.Debug("Processing XBRL table linkbase");
123 |
124 | ErrorLog tableErrorLog;
125 | this.TableModel = this.Instance.GenerateLayoutModel(XbrlUtils.GetTableLayoutOptions(), out tableErrorLog);
126 | if (this.TableModel == null || tableErrorLog.HasErrors)
127 | throw new ApplicationException(tableErrorLog.ToString());
128 |
129 | foreach (var context in this.Instance.Contexts)
130 | {
131 | if (context.Period.IsInstant && context.DimensionAspectValues.Count == 0)
132 | {
133 | this.ReportingContext = context;
134 | break;
135 | }
136 | }
137 | if (this.ReportingContext == null)
138 | {
139 | foreach (var context in this.Instance.Contexts)
140 | {
141 | if (context.DimensionAspectValues.Count == 0)
142 | {
143 | this.ReportingContext = context;
144 | break;
145 | }
146 | }
147 | }
148 |
149 | if (this.Instance.Units.Count > 0)
150 | {
151 | var units = new Dictionary();
152 | foreach (var unit in this.Instance.Units)
153 | {
154 | if (unit.AspectValue.IsMonetary)
155 | units.Add(unit.AspectValue.Iso4217Currency, 0);
156 | }
157 | foreach (var fact in this.Instance.Facts)
158 | {
159 | var item = fact as Xbrl.Item;
160 | if (item != null && item.UnitAspectValue != null && item.UnitAspectValue.IsMonetary)
161 | units[item.UnitAspectValue.Iso4217Currency] += 1;
162 | }
163 | var mostUsedCurrency = units.OrderByDescending(x => x.Value).First();
164 | if (mostUsedCurrency.Value > 0)
165 | this.ReportingCurrency = mostUsedCurrency.Key;
166 | }
167 |
168 | FilingIndicators = XbrlUtils.FilingIndicators(Instance);
169 | }
170 | }
171 | }
172 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/Table.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using Xbrl = Altova.RaptorXml.Xbrl;
3 |
4 | namespace XbrlTablesToExcel
5 | {
6 | public class Table
7 | {
8 | public Report Report;
9 | public Xbrl.Table.Layout.Table LayoutTable;
10 | public uint ZSlice;
11 |
12 | public Xbrl.Taxonomy.Dts Dts => Report.Dts;
13 | public Xbrl.Table.Table DefinitionTable => LayoutTable.DefinitionTable;
14 | public string Title => XbrlUtils.GetVerboseLabel(DefinitionTable);
15 | public string RcCode => XbrlUtils.GetRCCode(DefinitionTable);
16 | public string FilingIndicator => XbrlUtils.GetFilingIndicatorCode(DefinitionTable);
17 |
18 | public List OpenAspects;
19 | public bool HasOpenAspects => OpenAspects.Count > 0;
20 | public int OpenAspectCount => OpenAspects.Count;
21 |
22 | public int ColCount => (int)LayoutTable.Shape.X;
23 | public int RowCount => (int)LayoutTable.Shape.Y;
24 |
25 | public Xbrl.Table.Layout.Axis XAxis => LayoutTable.GetAxis(Xbrl.Table.AxisType.X);
26 | public Xbrl.Table.Layout.Axis YAxis => LayoutTable.GetAxis(Xbrl.Table.AxisType.Y);
27 | public Xbrl.Table.Layout.Axis ZAxis => LayoutTable.GetAxis(Xbrl.Table.AxisType.Z);
28 |
29 | public bool IsReported => Report.GetFilingIndicator(FilingIndicator);
30 |
31 |
32 | public Table(Report report, Xbrl.Table.Layout.Table table, uint zSlice = 0)
33 | {
34 | Report = report;
35 | LayoutTable = table;
36 | ZSlice = zSlice;
37 | OpenAspects = GetOpenAspects();
38 | }
39 |
40 | public bool IsRowEmpty(int y)
41 | {
42 | for (int x = 0; x < LayoutTable.Shape.X; ++x)
43 | {
44 | if (LayoutTable.GetCell((uint)x, (uint)y, ZSlice).Facts.Count > 0)
45 | return false;
46 | }
47 | return true;
48 | }
49 |
50 | public Xbrl.Table.Layout.Cell GetCell(int x, int y)
51 | {
52 | return LayoutTable.GetCell((uint)x, (uint)y, ZSlice);
53 | }
54 |
55 | public List GetOpenAspects()
56 | {
57 | var openAspects = new List();
58 | foreach (var header in YAxis.GetSlice(0))
59 | {
60 | if (header.DefinitionNode is Xbrl.Table.AspectNode)
61 | openAspects.Add(header.DefinitionNode as Xbrl.Table.AspectNode);
62 | }
63 | return openAspects;
64 | }
65 |
66 | public List GetZHeaders()
67 | {
68 | int row = 0;
69 | var zHeaders = new List();
70 | var constraints = GetCell(0, 0).ConstraintSet;
71 | foreach (var header in ZAxis.GetSlice(ZSlice))
72 | {
73 | string label = XbrlUtils.GetHeaderLabel(ZAxis, header, row);
74 | if (header.DefinitionNode is Xbrl.Table.AspectNode)
75 | {
76 | var aspect = (header.DefinitionNode as Xbrl.Table.AspectNode).ParticipatingAspect;
77 | var val = constraints[aspect];
78 | if (val == null)
79 | {
80 | label = string.Format("{0} null", label);
81 | }
82 | else if (val.Aspect.Type == Xbrl.AspectType.Dimension)
83 | {
84 | if (val.Aspect.Dimension.IsExplicit)
85 | label = XbrlUtils.GetLabel((val as Xbrl.ExplicitDimensionAspectValue).Value);
86 | else
87 | label = string.Format("{0} {1}", label, (val as Xbrl.TypedDimensionAspectValue).Value.SchemaNormalizedValue);
88 | }
89 | }
90 | zHeaders.Add(label);
91 | ++row;
92 | }
93 | return zHeaders;
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/TableTree.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text.RegularExpressions;
5 | using Xbrl = Altova.RaptorXml.Xbrl;
6 |
7 | namespace XbrlTablesToExcel
8 | {
9 | public struct TableTreeLine
10 | {
11 | public TableTreeLine(Table table, string title, int depth = 0)
12 | {
13 | Table = table;
14 | Title = title;
15 | Depth = depth;
16 | }
17 |
18 | public Table Table;
19 | public string Title;
20 | public int Depth;
21 |
22 | public bool IsGroup => Table == null;
23 | public bool IsTable => Table != null;
24 | public bool IsReported => Table?.IsReported ?? false;
25 | }
26 |
27 | public class TableTree : IEnumerable
28 | {
29 | public List Lines { get; set; }
30 | public int Count => Lines.Count;
31 |
32 | public IEnumerator GetEnumerator()
33 | {
34 | return Lines.GetEnumerator();
35 | }
36 | IEnumerator IEnumerable.GetEnumerator()
37 | {
38 | return GetEnumerator();
39 | }
40 |
41 | public TableTree(Report report)
42 | {
43 | Lines = new List();
44 |
45 | var netGroupTable = report.Dts.GetGenericNetwork("http://www.xbrl.org/2003/role/link", "http://www.eurofiling.info/xbrl/arcrole/group-table");
46 | if (netGroupTable != null)
47 | {
48 | foreach (var root in netGroupTable.Roots)
49 | {
50 | TraverseTableTree(report, netGroupTable, root);
51 | }
52 | }
53 | else
54 | {
55 | foreach (var tableSet in report.TableModel)
56 | {
57 | foreach (var table in tableSet)
58 | {
59 | for (uint z = 0; z < table.Shape.Z; ++z)
60 | {
61 | if (table.ContainsFactsInZSlice(z))
62 | {
63 | var tableInfo = new Table(report, table, z);
64 | Lines.Add(new TableTreeLine(tableInfo, tableInfo.Title));
65 | }
66 | }
67 | }
68 | }
69 | Lines.Sort((x, y) => x.Title.CompareTo(y.Title));
70 | }
71 | }
72 | void TraverseTableTree(Report report, Xbrl.Taxonomy.GenericRelationshipNetwork netGroupTable, object node, int depth = 0)
73 | {
74 | if (node is Xbrl.Table.Table)
75 | {
76 | var defTable = node as Xbrl.Table.Table;
77 | foreach (var table in XbrlUtils.FindTableSet(report.TableModel, defTable))
78 | {
79 | var tableInfo = new Table(report, table);
80 | if (table.GetAxis(Xbrl.Table.AxisType.Z).SliceCount > 1 || XbrlUtils.HasOpenAspectNodes(table.GetAxis(Xbrl.Table.AxisType.Z)))
81 | {
82 | Lines.Add(new TableTreeLine(null, tableInfo.Title, depth));
83 | for (uint z = 0; z < table.Shape.Z; ++z)
84 | {
85 | if (table.ContainsFactsInZSlice(z))
86 | {
87 | tableInfo = new Table(report, table, z);
88 | Lines.Add(new TableTreeLine(tableInfo, string.Join(", ", tableInfo.GetZHeaders()), depth + 1));
89 | }
90 | }
91 | }
92 | else if (table.ContainsFacts || tableInfo.IsReported)
93 | {
94 | Lines.Add(new TableTreeLine(tableInfo, tableInfo.Title, depth));
95 | }
96 | }
97 | }
98 | else
99 | {
100 | if (ShowGroupHeader(netGroupTable, node))
101 | Lines.Add(new TableTreeLine(null, XbrlUtils.GetLabel(node), depth++));
102 |
103 | foreach (var rel in netGroupTable.GetRelationshipsFrom(node))
104 | {
105 | TraverseTableTree(report, netGroupTable, rel.Target, depth);
106 | }
107 | }
108 | }
109 |
110 | static bool ShowGroupHeader(Xbrl.Taxonomy.GenericRelationshipNetwork netGroupTable, object node)
111 | {
112 | if (netGroupTable.GetRelationshipsFrom(node).Count == 1)
113 | {
114 | var child = netGroupTable.GetRelationshipsFrom(node).First().Target;
115 | if (child is Xbrl.Table.Table)
116 | {
117 | var tableLabel = Regex.Replace(XbrlUtils.GetVerboseLabel(child as Xbrl.Table.Table).ToLower(), @"[^0-9a-zA-Z]", string.Empty);
118 | var groupLabel = Regex.Replace(XbrlUtils.GetLabel(node).ToLower(), @"[^0-9a-zA-Z]", string.Empty);
119 | return !tableLabel.Contains(groupLabel);
120 | }
121 | }
122 | return true;
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/XbrlTablesToExcel.cs:
--------------------------------------------------------------------------------
1 | using Altova.RaptorXml;
2 | using CommandLine;
3 | using CommandLine.Text;
4 | using System;
5 | using System.Collections.Generic;
6 | using Xbrl = Altova.RaptorXml.Xbrl;
7 |
8 | namespace XbrlTablesToExcel
9 | {
10 | class XbrlTablesToExcel
11 | {
12 | static int Main(string[] args)
13 | {
14 | return Parser.Default.ParseArguments(args).MapResult((Options o) => Run(o), (err) => 1);
15 | }
16 |
17 | static int Run(Options o)
18 | {
19 | SetupLogger(o.LogFile);
20 |
21 | Xbrl.Taxonomy.Dts dts = null;
22 | if (o.EntryPointUrl != null)
23 | {
24 | Logger.Debug("Loading DTS {0}", o.EntryPointUrl);
25 | ErrorLog log;
26 | dts = Xbrl.Taxonomy.Dts.CreateFromUrl(o.EntryPointUrl, out log);
27 | if (log.HasErrors)
28 | {
29 | Logger.Error(log);
30 | return 1;
31 | }
32 | }
33 |
34 | var writer = new ExcelWriter(new DefaultTableStyle(), o.XOffset, o.YOffset, o.EmptyRowsAfterTitle);
35 | return ConvertReportToExcel(dts, writer, o.InputFile, o.OutputFile);
36 | }
37 |
38 | static int ConvertReportToExcel(Xbrl.Taxonomy.Dts dts, ExcelWriter writer, string fileIn, string fileOut)
39 | {
40 | try
41 | {
42 | var report = new Report(fileIn, dts);
43 | var wb = writer.WriteReport(report);
44 |
45 | Logger.Debug("Saving Excel workbook to {0}", fileOut);
46 | wb.SaveAs(fileOut);
47 | }
48 | catch (Exception e)
49 | {
50 | Logger.Error(e);
51 | return 1;
52 | }
53 |
54 | Logger.Info("Finished conversion of {0} to {1}", fileIn, fileOut);
55 | return 0;
56 | }
57 |
58 | class Options
59 | {
60 | [Usage()]
61 | public static IEnumerable Examples
62 | {
63 | get
64 | {
65 | return new List() {
66 | new Example("Convert XBRL instance to Excel workbook", new Options { InputFile = "input.xbrl", OutputFile = "output.xlsx" })
67 | };
68 | }
69 | }
70 |
71 | [Value(0, Required = true, MetaName = "XBRL", HelpText = "Input XBRL file")]
72 | public string InputFile { get; set; }
73 | [Value(1, Required = true, MetaName = "XLSX", HelpText = "Output XLSX file")]
74 | public string OutputFile { get; set; }
75 |
76 | [Option("dts", Required = false, HelpText = "Preloads the given DTS and uses it for validation of XBRL instance files. SchemaRefs in XBRL instance files will be ignored.")]
77 | public string EntryPointUrl { get; set; }
78 |
79 | [Option("x-offset", Default = 0, Required = false, HelpText = "Specify the number of empty columns that will be inserted before the generated table.")]
80 | public int XOffset { get; set; }
81 | [Option("y-offset", Default = 0, Required = false, HelpText = "Specify the number of empty rows that will be inserted before the generated table.")]
82 | public int YOffset { get; set; }
83 | [Option("empty-rows-after-title", Default = 1, Required = false, HelpText = "Specify the number of empty rows that will be inserted after the worksheet title.")]
84 | public int EmptyRowsAfterTitle { get; set; }
85 |
86 | [Option("log", Required = false, HelpText = "Log to file.")]
87 | public string LogFile { get; set; }
88 | }
89 |
90 | private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
91 | static void SetupLogger(string logfile)
92 | {
93 | // Rules for mapping loggers to targets
94 | var config = new NLog.Config.LoggingConfiguration();
95 | config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, new NLog.Targets.ConsoleTarget("logconsole") { Layout = new NLog.Layouts.SimpleLayout("${level:uppercase=true} ${message}") });
96 | if (logfile != null)
97 | config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, new NLog.Targets.FileTarget("logfile") { FileName = logfile });
98 |
99 | // Apply config
100 | NLog.LogManager.Configuration = config;
101 | }
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/XbrlTablesToExcel.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Release
6 | x64
7 | {D95FA9BA-8CD4-4C0E-9021-C150A8607808}
8 | Exe
9 | XbrlTablesToExcel
10 | XbrlTablesToExcel
11 | v4.8
12 | 512
13 | true
14 | false
15 | false
16 | Foreground
17 | 7
18 | Days
19 | false
20 | false
21 | true
22 | true
23 | 1
24 | 1.0.0.%2a
25 | false
26 | true
27 | true
28 |
29 |
30 |
31 | true
32 | bin\x64\Debug\
33 | DEBUG;TRACE
34 | full
35 | x64
36 | prompt
37 | MinimumRecommendedRules.ruleset
38 | true
39 |
40 |
41 | bin\x64\Release\
42 | TRACE
43 | true
44 | pdbonly
45 | x64
46 | prompt
47 | MinimumRecommendedRules.ruleset
48 | true
49 |
50 |
51 | false
52 |
53 |
54 | false
55 |
56 |
57 | LocalIntranet
58 |
59 |
60 |
61 | packages\ClosedXML.0.94.2\lib\net46\ClosedXML.dll
62 |
63 |
64 | packages\CommandLineParser.2.6.0\lib\net461\CommandLine.dll
65 |
66 |
67 | packages\DocumentFormat.OpenXml.2.9.1\lib\net46\DocumentFormat.OpenXml.dll
68 |
69 |
70 | packages\ExcelNumberFormat.1.0.7\lib\net20\ExcelNumberFormat.dll
71 |
72 |
73 | packages\FastMember.1.5.0\lib\net461\FastMember.dll
74 |
75 |
76 | packages\NLog.4.6.7\lib\net45\NLog.dll
77 |
78 |
79 | False
80 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
81 |
82 |
83 |
84 |
85 |
86 |
87 | packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll
88 |
89 |
90 | packages\System.IO.Packaging.4.5.0\lib\net46\System.IO.Packaging.dll
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 | False
121 | .NET Framework 3.5 SP1
122 | false
123 |
124 |
125 |
126 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/XbrlTablesToExcel.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28010.2041
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XbrlTablesToExcel", "XbrlTablesToExcel.csproj", "{D95FA9BA-8CD4-4C0E-9021-C150A8607808}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Release|x64 = Release|x64
11 | Debug|x64 = Debug|x64
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {D95FA9BA-8CD4-4C0E-9021-C150A8607808}.Release|x64.ActiveCfg = Release|x64
15 | {D95FA9BA-8CD4-4C0E-9021-C150A8607808}.Release|x64.Build.0 = Release|x64
16 | {D95FA9BA-8CD4-4C0E-9021-C150A8607808}.Debug|x64.ActiveCfg = Debug|x64
17 | {D95FA9BA-8CD4-4C0E-9021-C150A8607808}.Debug|x64.Build.0 = Debug|x64
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {6BB09363-AB3E-48EC-A2B0-EB87F14A237A}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/csharp/XBRLTablesToExcel/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/Directory.build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ..\build
6 | ..\..\build
7 | ..\..\build
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/ExternalFunction/ExternalFunction.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using Err = Altova.RaptorXml.ErrorLog;
16 | using XPath = Altova.RaptorXml.XPath;
17 |
18 | namespace XPathApiExamples
19 | {
20 | //The xpath.ExternalFunctions class provides a function extension mechanism and represents a collection of valid, pre-analyzed XPath.ExternalFunctionObject(s) extension functions.
21 | // It can be instantiated with the static method XPath.ExternalFunctions.Create.
22 | // The same XPath.ExternalFunctions object can be re-used on multiple xpath.CompileOptions, xquery.CompileOptions or xslt.CompileOptions
23 |
24 | // The xpath.ExternalFunctionObject class represents an extension function with native implementation based on the engine api.
25 | class FnExtNumericConv : XPath.ExternalFunctionObject
26 | {
27 | //The signature must have the form: EQName "(" ParamList? ")" ( "as" SequenceType )? and will be parsed and validated during the call to xpath.ExternalFunctions.Create(...)
28 | //A call to a function matching the name and arity provided by the signature in the constructor will call on the object the member method XPath.Sequence OnInvoke(XPath.SequenceList args, XPath.Session session, XPath.Instruction rInstruction) and propagate the returned xpath.Sequence to the executing expression.
29 |
30 | public FnExtNumericConv(string EQNamespaceUri)
31 | : base(string.Format("{0}integer-to-double($arg1 as xs:integer?) as xs:double?", EQNamespaceUri))
32 | {
33 | }
34 | public override XPath.Sequence OnInvoke(XPath.SequenceList args, XPath.Session session, XPath.Instruction instruction)
35 | {
36 | //Both the xpath.Sequence(s) from args and the returned xpath.Sequence are subject to the function conversion rules as defined in the W3C specifications.
37 | System.Console.WriteLine(string.Format(" >>External function object <{0}> called with {1} argument(s).", this.GetType().ToString(), args.Count));
38 | bool afterFirst = false;
39 | foreach (var s in args)
40 | {
41 | if (afterFirst)
42 | {
43 | System.Console.Write(", ");
44 | }
45 | XPathExecutor.PrintSequence(s);
46 | afterFirst = true;
47 | }
48 | System.Console.WriteLine(" >>Call to external function ends.");
49 | return args[0];
50 | }
51 | }
52 | class FnExtEnvVersion : XPath.ExternalFunctionObject
53 | {
54 | public FnExtEnvVersion(string EQNamespaceUri)
55 | : base(string.Format("{0}env-version() as xs:string?", EQNamespaceUri))
56 | {
57 | }
58 | public override XPath.Sequence OnInvoke(XPath.SequenceList args, XPath.Session session, XPath.Instruction instruction)
59 | {
60 | System.Console.WriteLine(string.Format(" >>External function object <{0}> called with {1} argument(s).", this.GetType().ToString(), args.Count));
61 | System.Console.WriteLine(" >>Call to external function ends.");
62 | return XPath.Sequence.FromItem(XPath.AtomicItem.FromString(System.Environment.Version.ToString(), session));
63 | }
64 | }
65 | public class ExternalFunction : XPathExecutor
66 | {
67 | const string FnNamespaceUri = "native-external-fn";
68 | static readonly string EQNamespaceUri = "Q{" + FnNamespaceUri + "}";
69 |
70 | protected override void InitCompileOptions(XPath.CompileOptions compileOptions)
71 | {
72 | base.InitCompileOptions(compileOptions);
73 | //XPath.ExternalFunctions.Create pre-processes the function signatures: syntax checking, resolving of namespace prefixes and schema type resolution.
74 | //If the ns_map or the schema parameter is None, then the default built -in values are used from XPath specification.
75 | compileOptions.StaticallyKnownNamespaces = new XPath.StringDict { { "ns1", FnNamespaceUri } };
76 | // In case of invalid signature syntax, unknown prefix or unknown type the xpath.ExternalFunctions is None and the xml.ErrorLog contains the error(s).
77 | var nativeFunctionLib = XPath.ExternalFunctions.Create(session, out Err err, null, null, new FnExtNumericConv(EQNamespaceUri), new FnExtEnvVersion(EQNamespaceUri));
78 | if (nativeFunctionLib == null || err.HasErrors)
79 | {
80 | PrintErrors("error compiling external function library", err);
81 | }
82 | else
83 | {
84 | compileOptions.ExternalFunctions = nativeFunctionLib;
85 | }
86 | }
87 | public override string GetDefaultExpr()
88 | {
89 | return string.Format("{0}integer-to-double(xs:untypedAtomic('1')) (:call to native .net code. Set a breakpoint in the OnInvoke(...) method to inspect parameters:),\n ns1:env-version()", EQNamespaceUri);
90 | }
91 |
92 | public static int Main(string[] args)
93 | {
94 | return SampleRunner.Run(args);
95 | }
96 |
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/ExternalFunction/ExternalFunction.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XPathApiExamples.ExternalFunction
10 | ..\..\build
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/ExternalVariables/ExternalVariables.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using XPath = Altova.RaptorXml.XPath;
16 | using Xsd = Altova.RaptorXml.Xsd;
17 |
18 | namespace XPathApiExamples
19 | {
20 | public class ExternalVariables : XPathExecutor
21 | {
22 | protected override void InitRuntimeOptions(XPath.RuntimeOptions runtimeOptions)
23 | {
24 | base.InitRuntimeOptions(runtimeOptions);
25 | //Create and set a variable
26 | //The variable name must be a valid QName item and the value an XPath.Sequence
27 | var varName = XPath.AtomicItem.FromQName(new Xsd.QName("x"), session);
28 | bool testError = false; //set to true to get a division by zero error;
29 | var varValue = testError ? XPath.AtomicItem.FromInt(0, session) : XPath.AtomicItem.FromDouble(0, session);
30 | runtimeOptions.ExternalVariables = new XPath.MapItem(session)
31 | {
32 | { varName, XPath.Sequence.FromItem(varValue) }
33 | };
34 | }
35 |
36 | public override string GetDefaultExpr()
37 | {
38 | return "(-1 to 1)!(. div $x) (:This is an XPath comment: expect -INF, NaN, INF when $x is of type xs:double, or Division by zero error if $x is instance of xs:integer:)";
39 | }
40 |
41 | public static int Main(string[] args)
42 | {
43 | return SampleRunner.Run(args);
44 | }
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/ExternalVariables/ExternalVariables.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XPathApiExamples.ExternalVariables
10 | ..\..\build
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/GettingStarted/GettingStarted.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using Err = Altova.RaptorXml.ErrorLog;
16 | using XPath = Altova.RaptorXml.XPath;
17 |
18 | namespace XPathApiExamples
19 | {
20 | public interface IExecuteXPath
21 | {
22 | int ExecuteXPath(string strExpr);
23 | string GetDefaultExpr();
24 | }
25 | public class XPathExecutor : IExecuteXPath
26 | {
27 | protected XPath.Session session;
28 |
29 | public XPathExecutor()
30 | {
31 | //Step 1: create an XPath.Session object that holds and keeps alive the data required by the xpath/xquery/xslt engines
32 | session = new XPath.Session();
33 | }
34 |
35 | public int ExecuteXPath(string strExpr)
36 | {
37 | System.Console.WriteLine("Executing xpath: " + strExpr);
38 | //Step 2: create the options object which will be used for the static analysis of the expression
39 | var compileOptions = new XPath.CompileOptions(session);
40 | InitCompileOptions(compileOptions);
41 |
42 | //Step 3: parse and statically analyze the expression to create an expression that can be used for multiple executions
43 | var expr = XPath.Expression.Compile(strExpr, compileOptions, out Err logCompile);
44 |
45 | //Step 3a: check for errors
46 | if (expr == null || logCompile.HasErrors)
47 | {
48 | PrintErrors(string.Format("Failed to compile xpath expression {0}.", strExpr), logCompile);
49 | return 1;
50 | }
51 |
52 | //Step 4: create the runtime options used in the dynamic evaluation phase, this can be used to specify dynamic context components - ex. different values for expression.Execute calls
53 | var runtimeOptions = new XPath.RuntimeOptions(session);
54 | InitRuntimeOptions(runtimeOptions);
55 |
56 | //Step 5: now execute the expression
57 | var result = expr.Execute(runtimeOptions, out Err logExecute);
58 |
59 | //Step 5a: check for runtime errors
60 | if (result == null || logExecute.HasErrors)
61 | {
62 | PrintErrors("Failed to execute the xpath expression", logExecute);
63 | return 2;
64 | }
65 |
66 | //Step 6: the result is an XPath.Sequence, do something with it
67 | // ex. print it's elements to the console
68 | PrintSequence(result);
69 |
70 | return 0;
71 | }
72 |
73 | protected virtual void InitCompileOptions(XPath.CompileOptions compileOptions)
74 | {
75 | //ex. specify the xpath spec that should be used
76 | compileOptions.Version = XPath.Version.V31;
77 |
78 | //static-base-uri is used to resolve relative paths ex. in fn:doc, fn:unparsed-text, etc.
79 | //Note: compileOptions.StaticBaseUri must be in the lexical space of xs:anyURI
80 | compileOptions.StaticBaseUri = new System.Uri(System.IO.Directory.GetCurrentDirectory()).AbsoluteUri + '/' + System.Uri.EscapeDataString(System.IO.Path.GetRandomFileName());
81 | }
82 |
83 | protected virtual void InitRuntimeOptions(XPath.RuntimeOptions runtimeOptions)
84 | {
85 | }
86 |
87 | //print the Altova.RaptorXml.ErrorLog to the console
88 | protected static void PrintErrors(string msg, Err log)
89 | {
90 | System.Console.WriteLine(msg);
91 | foreach (var error in log)
92 | {
93 | System.Console.WriteLine(error.Text);
94 | }
95 | }
96 | public static void PrintSequence(XPath.Sequence items)
97 | {
98 | //print the size of the sequence and the contained items type and string value to the console
99 | //an XPath.Sequence implements the IEnumerable interface
100 | System.Console.Write(string.Format("XPath.Sequence[{0}]{{", items.Count)); //number of XPath.Items
101 | string prefix = "";
102 | //foreach XPath.Item in the Sequence
103 | foreach (var item in items)
104 | {
105 | System.Console.Write(string.Format(prefix + "{0}('{1}')", item.GetTypeName(), item.ToString()));
106 | prefix = ", ";
107 | }
108 | System.Console.WriteLine("}");
109 | }
110 |
111 | public virtual string GetDefaultExpr()
112 | {
113 | return "'Hello from xpath!', 'The current date/time is:', current-dateTime(), static-base-uri()";
114 | }
115 |
116 | }
117 |
118 | public class SampleRunner where T : IExecuteXPath, new()
119 | {
120 | public static int Run(string[] args)
121 | {
122 | var o = new T();
123 | string strExpr = args.Length > 0 ? args[0] : o.GetDefaultExpr();
124 | return o.ExecuteXPath(strExpr);
125 | }
126 | };
127 |
128 | public class GettingStarted
129 | {
130 | public static int Main(string[] args)
131 | {
132 | return SampleRunner.Run(args);
133 | }
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/GettingStarted/GettingStarted.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XPathApiExamples.GettingStarted
10 | ..\..\build
11 |
12 |
13 |
14 |
15 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/InitialContextItem/InitialContextItem.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using XPath = Altova.RaptorXml.XPath;
16 |
17 | namespace XPathApiExamples
18 | {
19 | public class InitialContextItem : XPathExecutor
20 | {
21 | protected override void InitRuntimeOptions(XPath.RuntimeOptions runtimeOptions)
22 | {
23 | base.InitRuntimeOptions(runtimeOptions);
24 | //Create and set the initial context item
25 | runtimeOptions.InitialContext = XPath.AtomicItem.FromInt(1337, session);
26 | }
27 | public override string GetDefaultExpr()
28 | {
29 | return "if(. instance of xs:numeric) then 'numeric' else 'non-numeric', ., 'context position is ' || position(), 'context size is ' || last()";
30 | }
31 |
32 | public static int Main(string[] args)
33 | {
34 | return SampleRunner.Run(args);
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/InitialContextItem/InitialContextItem.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XPathApiExamples.InitialContextItem
10 | ..\..\build
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/InitialContextXmlDocument/InitialContextXmlDocument.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using Err = Altova.RaptorXml.ErrorLog;
16 | using Xml = Altova.RaptorXml.Xml;
17 | using XPath = Altova.RaptorXml.XPath;
18 |
19 | namespace XPathApiExamples
20 | {
21 | public class InitialContextXmlDocument : XPathExecutor
22 | {
23 | Xml.Instance LoadedXmlDoc = null;
24 |
25 | void LoadXmlDoc()
26 | {
27 | if (LoadedXmlDoc == null)
28 | {
29 | var fileName = @"c:\Program Files\Altova\RaptorXMLXBRLServer2025\examples\NanonullOrg.xml";
30 | var xmlDoc = Xml.Instance.CreateFromUrl(fileName, out Err loadErr);
31 | if (xmlDoc == null || loadErr.HasErrors)
32 | {
33 | PrintErrors("error loading document", loadErr);
34 | }
35 | else
36 | {
37 | LoadedXmlDoc = xmlDoc;
38 | }
39 | }
40 | }
41 |
42 | protected override void InitCompileOptions(XPath.CompileOptions compileOptions)
43 | {
44 | base.InitCompileOptions(compileOptions);
45 | LoadXmlDoc();
46 | if (LoadedXmlDoc != null)
47 | {
48 | compileOptions.StaticallyKnownNamespaces = new XPath.StringDict() { { "ns1", LoadedXmlDoc.DocumentElement.NamespaceName } };
49 | }
50 | }
51 | protected override void InitRuntimeOptions(XPath.RuntimeOptions runtimeOptions)
52 | {
53 | base.InitRuntimeOptions(runtimeOptions);
54 | if (LoadedXmlDoc != null)
55 | {
56 | //Create and set the initial context node
57 | runtimeOptions.InitialContext = XPath.NodeItem.FromInformationItem(LoadedXmlDoc.DocumentItem, session);
58 | }
59 | }
60 | public override string GetDefaultExpr()
61 | {
62 | return "distinct-values(/ns1:OrgChart//*:Department/*:Name) (:uses wildcard to match the elements regardless of their namespace:)";
63 | }
64 |
65 | public static int Main(string[] args)
66 | {
67 | return SampleRunner.Run(args);
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/InitialContextXmlDocument/InitialContextXmlDocument.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XPathApiExamples.InitialContextXmlDocument
10 | ..\..\build
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/NamespacePrefixes/NamespacePrefixes.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using XPath = Altova.RaptorXml.XPath;
16 |
17 | namespace XPathApiExamples
18 | {
19 | public class NamespacePrefixes : XPathExecutor
20 | {
21 | const string MyNamespaceUri = "my-namespace-uri";
22 | protected override void InitCompileOptions(XPath.CompileOptions compileOptions)
23 | {
24 | base.InitCompileOptions(compileOptions);
25 | compileOptions.StaticallyKnownNamespaces = new XPath.StringDict() { { "prefix1", MyNamespaceUri } };
26 | }
27 | public override string GetDefaultExpr()
28 | {
29 | return string.Format("parse-xml('')//prefix1:*", MyNamespaceUri);
30 | }
31 |
32 | public static int Main(string[] args)
33 | {
34 | return SampleRunner.Run(args);
35 | }
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/NamespacePrefixes/NamespacePrefixes.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XPathApiExamples.NamespacePrefixes
10 | ..\..\build
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/README.md:
--------------------------------------------------------------------------------
1 | # RaptorXML-Examples using the xpath api in C# #
2 |
3 | Examples for using the [C# API](https://www.altova.com/manual/en/raptorapi/dotnetapiv2/2.10.0/html/html/R_Project_Documentation.html) of [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html).
4 |
5 | ##### GettingStarted
6 | * an example demonstrating how to set-up a session, compile and execute an xpath expression, handling errors and printing the result sequence.
7 |
8 | ##### ExternalVariables
9 | * an example demonstrating how to specify the name and value for an variable.
10 |
11 | ##### NamespacePrefixes
12 | * an example demonstrating how to set an in-scope namespace prefix map in the CompileOptions.
13 |
14 | #### InitialContextItem
15 | * an example demonstrating how to set the initial context item for an expression execution.
16 |
17 | #### InitialContextXmlDocument
18 | * an example demonstrating how to load an XML file and select nodes using the path expressions and how to work with namespaces.
19 |
20 | #### ExternalFunction
21 | * an example demonstrating how to use the ExternalFunctions mechanism to provide external extension function(s) with native callback invocation based on specialization(s) of XPath.ExternalFunctionObject(s).
22 |
23 | #### TraceMsg
24 | * an example demonstrating how to display the fn:trace messages using the TraceMsgCallbackObject
25 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/TraceMsg/TraceMsg.cs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Altova GmbH
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | using Altova.RaptorXml.XPath;
16 | using XPath = Altova.RaptorXml.XPath;
17 |
18 | namespace XPathApiExamples
19 | {
20 | public class TraceMsgCallback : XPath.TraceMsgCallbackObject
21 | {
22 | public TraceMsgCallback(XPath.Session session)
23 | : base(session)
24 | {
25 | }
26 |
27 | public override void OnFnTrace(Sequence value, AtomicItem label)
28 | {
29 | System.Console.WriteLine(string.Format(" >>Trace begin - label: '{0}'", label.ToString()));
30 | System.Console.Write(" value: ");
31 | XPathExecutor.PrintSequence(value);
32 | System.Console.WriteLine(" >>Trace end");
33 | }
34 | }
35 | public class TraceMsg : XPathExecutor
36 | {
37 | protected override void InitRuntimeOptions(XPath.RuntimeOptions runtimeOptions)
38 | {
39 | base.InitRuntimeOptions(runtimeOptions);
40 | runtimeOptions.TraceCallback = new TraceMsgCallback(session);
41 | }
42 | public override string GetDefaultExpr()
43 | {
44 | return "2!trace(math:sqrt(.), 'Calculating sqrt of ' || .)";
45 | }
46 |
47 | public static int Main(string[] args)
48 | {
49 | return SampleRunner.Run(args);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/TraceMsg/TraceMsg.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XPathApiExamples.TraceMsg
10 | ..\..\build
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XPathApiExamples/XPathApiExamples.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.0.31903.59
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GettingStarted", "GettingStarted\GettingStarted.csproj", "{48CEDD97-D8BD-4951-B892-2552011C448A}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExternalVariables", "ExternalVariables\ExternalVariables.csproj", "{3ABB6200-9EA2-4038-9BB0-5A80668F8130}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InitialContextXmlDocument", "InitialContextXmlDocument\InitialContextXmlDocument.csproj", "{AA8D96D9-C6D1-4334-A5BA-222E7DDBE84C}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NamespacePrefixes", "NamespacePrefixes\NamespacePrefixes.csproj", "{BBE7F30C-880E-4685-B2CF-5626348E8B3F}"
13 | EndProject
14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InitialContextItem", "InitialContextItem\InitialContextItem.csproj", "{C706E1D4-24CF-4B13-9969-7B04D32BF124}"
15 | EndProject
16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TraceMsg", "TraceMsg\TraceMsg.csproj", "{EFB43655-75AF-4F60-892C-9361355CC52D}"
17 | EndProject
18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExternalFunction", "ExternalFunction\ExternalFunction.csproj", "{D60E522D-1CF6-465B-A50F-321FDAEA5DD4}"
19 | EndProject
20 | Global
21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
22 | Debug|x64 = Debug|x64
23 | Release|x64 = Release|x64
24 | EndGlobalSection
25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
26 | {48CEDD97-D8BD-4951-B892-2552011C448A}.Debug|x64.ActiveCfg = Debug|x64
27 | {48CEDD97-D8BD-4951-B892-2552011C448A}.Debug|x64.Build.0 = Debug|x64
28 | {48CEDD97-D8BD-4951-B892-2552011C448A}.Release|x64.ActiveCfg = Release|x64
29 | {48CEDD97-D8BD-4951-B892-2552011C448A}.Release|x64.Build.0 = Release|x64
30 | {3ABB6200-9EA2-4038-9BB0-5A80668F8130}.Debug|x64.ActiveCfg = Debug|x64
31 | {3ABB6200-9EA2-4038-9BB0-5A80668F8130}.Debug|x64.Build.0 = Debug|x64
32 | {3ABB6200-9EA2-4038-9BB0-5A80668F8130}.Release|x64.ActiveCfg = Release|x64
33 | {3ABB6200-9EA2-4038-9BB0-5A80668F8130}.Release|x64.Build.0 = Release|x64
34 | {AA8D96D9-C6D1-4334-A5BA-222E7DDBE84C}.Debug|x64.ActiveCfg = Debug|x64
35 | {AA8D96D9-C6D1-4334-A5BA-222E7DDBE84C}.Debug|x64.Build.0 = Debug|x64
36 | {AA8D96D9-C6D1-4334-A5BA-222E7DDBE84C}.Release|x64.ActiveCfg = Release|x64
37 | {AA8D96D9-C6D1-4334-A5BA-222E7DDBE84C}.Release|x64.Build.0 = Release|x64
38 | {BBE7F30C-880E-4685-B2CF-5626348E8B3F}.Debug|x64.ActiveCfg = Debug|x64
39 | {BBE7F30C-880E-4685-B2CF-5626348E8B3F}.Debug|x64.Build.0 = Debug|x64
40 | {BBE7F30C-880E-4685-B2CF-5626348E8B3F}.Release|x64.ActiveCfg = Release|x64
41 | {BBE7F30C-880E-4685-B2CF-5626348E8B3F}.Release|x64.Build.0 = Release|x64
42 | {C706E1D4-24CF-4B13-9969-7B04D32BF124}.Debug|x64.ActiveCfg = Debug|x64
43 | {C706E1D4-24CF-4B13-9969-7B04D32BF124}.Debug|x64.Build.0 = Debug|x64
44 | {C706E1D4-24CF-4B13-9969-7B04D32BF124}.Release|x64.ActiveCfg = Release|x64
45 | {C706E1D4-24CF-4B13-9969-7B04D32BF124}.Release|x64.Build.0 = Release|x64
46 | {EFB43655-75AF-4F60-892C-9361355CC52D}.Debug|x64.ActiveCfg = Debug|x64
47 | {EFB43655-75AF-4F60-892C-9361355CC52D}.Debug|x64.Build.0 = Debug|x64
48 | {EFB43655-75AF-4F60-892C-9361355CC52D}.Release|x64.ActiveCfg = Release|x64
49 | {EFB43655-75AF-4F60-892C-9361355CC52D}.Release|x64.Build.0 = Release|x64
50 | {D60E522D-1CF6-465B-A50F-321FDAEA5DD4}.Debug|x64.ActiveCfg = Debug|x64
51 | {D60E522D-1CF6-465B-A50F-321FDAEA5DD4}.Debug|x64.Build.0 = Debug|x64
52 | {D60E522D-1CF6-465B-A50F-321FDAEA5DD4}.Release|x64.ActiveCfg = Release|x64
53 | {D60E522D-1CF6-465B-A50F-321FDAEA5DD4}.Release|x64.Build.0 = Release|x64
54 | EndGlobalSection
55 | GlobalSection(SolutionProperties) = preSolution
56 | HideSolutionNode = FALSE
57 | EndGlobalSection
58 | GlobalSection(ExtensibilityGlobals) = postSolution
59 | SolutionGuid = {FA61CCEE-1D9A-47EE-93FC-F412FA8FD74A}
60 | EndGlobalSection
61 | EndGlobal
62 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XQueryApiExamples/Directory.build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ..\build
6 | ..\..\build
7 | ..\..\build
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XQueryApiExamples/README.md:
--------------------------------------------------------------------------------
1 | # RaptorXML-Examples using the xpath api in C# #
2 |
3 | Examples for using the [C# API](https://www.altova.com/manual/en/raptorapi/dotnetapiv2/2.10.0/html/html/R_Project_Documentation.html) of [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html).
4 |
5 | ##### XQuerySample
6 | * an example demonstrating how to set-up a session, compile and execute an xquery expression, with callback extension functions to the .net environment
7 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XQueryApiExamples/XQueryApiExamples.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.10.35201.131
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XQuerySample", "XQuerySample\XQuerySample.csproj", "{568641C1-A219-43FB-A512-B8FA9EDD43D5}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|x64 = Debug|x64
11 | Release|x64 = Release|x64
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {568641C1-A219-43FB-A512-B8FA9EDD43D5}.Debug|x64.ActiveCfg = Debug|x64
15 | {568641C1-A219-43FB-A512-B8FA9EDD43D5}.Debug|x64.Build.0 = Debug|x64
16 | {568641C1-A219-43FB-A512-B8FA9EDD43D5}.Release|x64.ActiveCfg = Release|x64
17 | {568641C1-A219-43FB-A512-B8FA9EDD43D5}.Release|x64.Build.0 = Release|x64
18 | {334C2FEC-BB92-4BA8-B58E-10BF6F4EC806}.Debug|x64.ActiveCfg = Debug|x64
19 | {334C2FEC-BB92-4BA8-B58E-10BF6F4EC806}.Debug|x64.Build.0 = Debug|x64
20 | {334C2FEC-BB92-4BA8-B58E-10BF6F4EC806}.Release|x64.ActiveCfg = Release|x64
21 | {334C2FEC-BB92-4BA8-B58E-10BF6F4EC806}.Release|x64.Build.0 = Release|x64
22 | EndGlobalSection
23 | GlobalSection(SolutionProperties) = preSolution
24 | HideSolutionNode = FALSE
25 | EndGlobalSection
26 | GlobalSection(ExtensibilityGlobals) = postSolution
27 | SolutionGuid = {95D8DE48-CFC5-4176-8985-CF15064F249E}
28 | EndGlobalSection
29 | EndGlobal
30 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XQueryApiExamples/XQuerySample/XQuerySample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XQueryApiExamples.GettingStarted
10 | ..\..\build
11 |
12 |
13 |
14 |
15 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XSLTApiExamples/Directory.build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ..\..\build
6 | ..\..\build
7 | ..\..\build
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XSLTApiExamples/QuickIntroSample/Program.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net48
5 | disable
6 | disable
7 | x64;
8 | MyApp.Program
9 | ..\..\build
10 |
11 |
12 |
13 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XSLTApiExamples/QuickIntroSample/QuickIntroSample.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.5.002.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Program", "Program.csproj", "{DADA41CB-FBBF-4218-B8F9-1EA4F3AF1FE0}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|x64 = Debug|x64
11 | Release|x64 = Release|x64
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {DADA41CB-FBBF-4218-B8F9-1EA4F3AF1FE0}.Debug|x64.ActiveCfg = Debug|x64
15 | {DADA41CB-FBBF-4218-B8F9-1EA4F3AF1FE0}.Debug|x64.Build.0 = Debug|x64
16 | {DADA41CB-FBBF-4218-B8F9-1EA4F3AF1FE0}.Release|x64.ActiveCfg = Release|x64
17 | {DADA41CB-FBBF-4218-B8F9-1EA4F3AF1FE0}.Release|x64.Build.0 = Release|x64
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {29FA6A47-9512-46DF-B50D-A7283D73CF0A}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XSLTApiExamples/README.md:
--------------------------------------------------------------------------------
1 | # RaptorXML-Examples using the xpath api in C# #
2 |
3 | Examples for using the [C# API](https://www.altova.com/manual/en/raptorapi/dotnetapiv2/2.10.0/html/html/R_Project_Documentation.html) of [RaptorXML+XBRL Server](http://www.altova.com/raptorxml.html).
4 |
5 | ##### XSLTSample
6 | * an example demonstrating how to set-up a session, compile and execute an xslt stylesheet, with callback extension functions to the .net environment
7 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XSLTApiExamples/XSLTApiExamples.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.10.35201.131
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XSLTSample", "XSLTSample\XSLTSample.csproj", "{C0E04A26-DD87-4109-9224-66B512CB7BFB}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|x64 = Debug|x64
11 | Release|x64 = Release|x64
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {C0E04A26-DD87-4109-9224-66B512CB7BFB}.Debug|x64.ActiveCfg = Debug|x64
15 | {C0E04A26-DD87-4109-9224-66B512CB7BFB}.Debug|x64.Build.0 = Debug|x64
16 | {C0E04A26-DD87-4109-9224-66B512CB7BFB}.Release|x64.ActiveCfg = Release|x64
17 | {C0E04A26-DD87-4109-9224-66B512CB7BFB}.Release|x64.Build.0 = Release|x64
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {D34BAE1B-DD80-48B3-AE09-C4F5EB41D850}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/csharp/XPathXQueryXslt/XSLTApiExamples/XSLTSample/XSLTSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48
6 | disable
7 | disable
8 | x64;
9 | XSLTApiExamples.GettingStarted
10 | ..\..\build
11 |
12 |
13 |
14 |
15 | C:\Program Files\Altova\RaptorXMLXBRLServer2025\bin\raptorxmlxbrlapi.dll
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/custom_validation.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script uses Altova RaptorXML+XBRL Python API v2 to demonstrate how to add additional validation rules and report custom errors.
18 | #
19 | # Example invocations:
20 | #
21 | # Validate a single filing
22 | # raptorxmlxbrl valxbrl --script=custom_validation.py instance.xbrl
23 | # Validate a single filing with additional options
24 | # raptorxmlxbrl valxbrl --script=custom_validation.py --script-param=myvalue:456 instance.xbrl
25 | #
26 | # Using Altova RaptorXML+XBRL Server with XMLSpy client:
27 | #
28 | # 1a. Copy custom_validation.py to the Altova RaptorXML Server script directory /etc/scripts/ (default C:\Program Files\Altova\RaptorXMLXBRLServer2016\etc\scripts\) or
29 | # 1b. Edit the tag in /etc/server_config.xml
30 | # 2. Start Altova RaptorXML+XBRL server.
31 | # 3. Start Altova XMLSpy, open Tools|Manage Raptor Servers... and connect to the running server
32 | # 4. Create a new configuration and rename it to e.g. "CUSTOM"
33 | # 5. Select the XBRL Instance property page and then set the script property to custom_validation.py
34 | # 6. Select the new "CUSTOM" configuration in Tools|Raptor Servers and Configurations
35 | # 7. Open an instance file
36 | # 8. Validate instance file with XML|Validate XML on Server (Ctrl+F8)
37 |
38 |
39 | from altova import *
40 | import decimal
41 |
42 |
43 | def check_custom_rules(instance, error_log, myvalue):
44 | # For demonstration purposes, let's say that only the numeric value
45 | # myvalue is ever allowed in XBRL facts!
46 |
47 | # Iterate over every fact in the instance
48 | for fact in instance.facts:
49 | # Ignore tuples
50 | if isinstance(fact, xbrl.Tuple):
51 | continue
52 |
53 | if fact.concept.is_numeric():
54 | # Check the effective numeric value (which takes also the precision
55 | # and decimals attributes into account)
56 | if fact.effective_numeric_value != myvalue:
57 | # Raise error that the value is incorrect
58 | # location can be used to specify the default location for the
59 | # whole error line. XMLSpy automatically jumps to the location
60 | # of the first error after validation.
61 | error_log.report(xbrl.Error.create('Value {fact:value} of fact {fact} must be equal to {myvalue}.', location='fact:value', fact=fact, myvalue=xml.Error.Param(
62 | str(myvalue), tooltip='Use the myvalue option to specify a different value!', quotes=False)))
63 | else:
64 | # Raise error that the type is incorrect
65 | # location can be used to specify the default location for the
66 | # whole error line. XMLSpy automatically jumps to the location of
67 | # the first error after validation.
68 | error_log.report(xbrl.Error.create(
69 | 'Fact {fact} has non-numeric type {type}.', location='fact', fact=fact, type=fact.concept.type_definition))
70 |
71 | # Main entry point, will be called by RaptorXML after the XBRL instance
72 | # validation job has finished
73 |
74 |
75 | def on_xbrl_finished(job, instance):
76 | # instance object will be None if XBRL 2.1 validation was not successful
77 | if instance:
78 | check_custom_rules(instance, job.error_log, decimal.Decimal(
79 | job.script_params.get('myvalue', '123')))
80 |
--------------------------------------------------------------------------------
/dimensional_relationship_set_traversal.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script uses RaptorXML Python API v2 to print out all the DRS (Dimensional relationship set) networks found in the DTS as simple trees
18 | #
19 | # Example invocation:
20 | # raptorxmlxbrl valxbrl --script=dimensional_relationship_set_traversal.py
21 | # nanonull.xbrl
22 |
23 |
24 | from altova import *
25 |
26 |
27 | def concept_label(concept, label_role=None):
28 | if not label_role:
29 | label_role = xbrl.taxonomy.ROLE_LABEL
30 | # Find all labels matching the given criteria
31 | labels = list(concept.labels(label_role=label_role, lang='en'))
32 | if not labels:
33 | # If not labels are found fallback to concept QName
34 | return str(concept.qname)
35 | # Return text of first label found
36 | return labels[0].text
37 |
38 |
39 | def print_domain_member(drs, linkrole, domain_member, level=1):
40 | print('\t' * level, concept_label(domain_member))
41 |
42 | # Iterate over domain-member relationships
43 | for rel in drs.domain_member_relationships(domain_member, linkrole):
44 | # Access the additional definitionArc attributes using rel.usable
45 | print_domain_member(drs, linkrole, rel.target, level + 1)
46 |
47 |
48 | def print_dimension(drs, linkrole, dimension, level=1):
49 | print('\t' * level, concept_label(dimension))
50 |
51 | # Iterate over dimension-domain relationships
52 | for rel in drs.dimension_domain_relationships(dimension, linkrole):
53 | print_domain_member(drs, linkrole, rel.target, level + 1)
54 |
55 |
56 | def print_hypercube(drs, linkrole, hypercube, all, level=1):
57 | if all:
58 | print('\t' * level, concept_label(hypercube))
59 | else:
60 | print('\t' * level, '!', concept_label(hypercube))
61 |
62 | # Iterate over hypercube-dimension relationships
63 | for rel in drs.hypercube_dimension_relationships(hypercube, linkrole):
64 | # Access the additional definitionArc attributes using rel.closed and
65 | # rel.context_element
66 | print_dimension(drs, linkrole, rel.target, level + 1)
67 |
68 |
69 | def print_primary_item(drs, linkrole, pi, level=1):
70 | print('\t' * level, concept_label(pi))
71 |
72 | # Iterate over all/notAll relationships
73 | for rel in drs.hashypercube_relationships(pi, linkrole):
74 | print_hypercube(drs, linkrole, rel.target, rel.arcrole ==
75 | xbrl.taxonomy.ARCROLE_ALL, level + 1)
76 |
77 | # Iterate over domain-member relationships
78 | for rel in drs.domain_member_relationships(pi, linkrole):
79 | print_primary_item(drs, linkrole, rel.target, level + 1)
80 |
81 |
82 | def linkrole_definition(dts, linkrole):
83 | try:
84 | # Return the human readable roleType definition string for the given
85 | # linkrole if present
86 | return dts.role_type(linkrole).definition.value
87 | except:
88 | # Otherwise just return the linkrole URI
89 | return linkrole
90 |
91 |
92 | def print_dimensional_relationship_set(dts, linkrole):
93 | print(linkrole_definition(dts, linkrole))
94 |
95 | drs = dts.dimensional_relationship_set()
96 | # Iterate over all root primary item concepts
97 | for pi in drs.roots(linkrole):
98 | print_primary_item(drs, linkrole, pi)
99 |
100 |
101 | def print_dimensional_networks(dts):
102 | # Iterate over all definition extended link roles
103 | for linkrole in dts.definition_link_roles(None):
104 | print_dimensional_relationship_set(dts, linkrole)
105 |
106 | # Main entry point, will be called by RaptorXML after the XBRL taxonomy
107 | # (DTS) validation job has finished
108 |
109 |
110 | def on_dts_finished(job, dts):
111 | # dts object will be None if validation was not successful
112 | if dts:
113 | print_dimensional_networks(dts)
114 |
115 | # Main entry point, will be called by RaptorXML after the XBRL instance
116 | # validation job has finished
117 |
118 |
119 | def on_xbrl_finished(job, instance):
120 | # instance object will be None if validation was not successful
121 | if instance:
122 | print_dimensional_networks(instance.dts)
123 |
--------------------------------------------------------------------------------
/entry_points.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script contains a minimal stub implementation for each entry point function in RaptorXML Python API v2.
18 | #
19 | # Example invocation:
20 | # raptorxml valxml-withxsd --streaming=false --script=entry_points.py
21 | # ExpReport.xml
22 |
23 | from altova import *
24 |
25 | # This entry point will be called by RaptorXML after the XML instance
26 | # validation job (valxml-withxsd) has finished
27 |
28 |
29 | def on_xsi_finished(job, instance):
30 | # instance object will be None if XML validation was not successful
31 | print('on_xsi_finished() was called')
32 |
33 | # This entry point will be called by RaptorXML after the DTD validation
34 | # job (valdtd) has finished (since v2.1)
35 |
36 |
37 | def on_dtd_finished(job, dtd):
38 | # dtd object will be None if DTD validation was not successful
39 | print('on_dtd_finished() was called')
40 |
41 | # This entry point will be called by RaptorXML after the XML Schema
42 | # validation job (valxsd) has finished
43 |
44 |
45 | def on_xsd_finished(job, schema):
46 | # schema object will be None if XML Schema validation was not successful
47 | print('on_xsd_finished() was called')
48 |
49 | # This entry point will be called by RaptorXML+XBRL after the XBRL DTS
50 | # validation job (valdts) has finished
51 |
52 |
53 | def on_dts_finished(job, schema):
54 | # dts object will be None if XBRL DTS validation was not successful
55 | print('on_dts_finished() was called')
56 |
57 | # This entry point will be called by RaptorXML+XBRL after the XBRL
58 | # instance validation job (valxbrl) has finished
59 |
60 |
61 | def on_xbrl_finished(job, instance):
62 | # instance object will be None if XBRL 2.1 validation was not successful
63 | print('on_xbrl_finished() was called')
64 |
--------------------------------------------------------------------------------
/instance_statistics.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script uses RaptorXML Python API v2 to print out some statistics about the instance and its supporting DTS.
18 | #
19 | # Example invocation:
20 | # raptorxmlxbrl valxbrl --script=instance_statistics.py nanonull.xbrl
21 |
22 | from altova import *
23 |
24 |
25 | def print_dts_statistics(dts):
26 |
27 | # Please note that many taxonomy.DTS properties return generator objects
28 | # which cannot be used with len() directly
29 |
30 | print('DTS contains %d documents' % sum(1 for _ in dts.documents))
31 | print('DTS contains %d taxonomy documents' %
32 | sum(1 for _ in dts.taxonomy_schemas))
33 | print('DTS contains %d linkbase documents' % sum(1 for _ in dts.linkbases))
34 |
35 | print('DTS contains %d concepts' % sum(1 for _ in dts.concepts))
36 | # Please note that hypercube and dimension concepts are also members of
37 | # the xbrli:item substitution group
38 | print('DTS contains %d item concepts' % (sum(1 for _ in dts.items) -
39 | sum(1 for _ in dts.hypercubes) - sum(1 for _ in dts.dimensions)))
40 | print('DTS contains %d tuple concepts' % sum(1 for _ in dts.tuples))
41 | print('DTS contains %d hypercubes' % sum(1 for _ in dts.hypercubes))
42 | print('DTS contains %d dimensions' % sum(1 for _ in dts.dimensions))
43 |
44 | print('DTS contains %d formula parameters' %
45 | sum(1 for _ in dts.parameters))
46 | print('DTS contains %d formulas' % sum(1 for _ in dts.formulas))
47 | print('DTS contains %d assertions' % sum(1 for _ in dts.assertions))
48 | print('DTS contains %d tables' % sum(1 for _ in dts.tables))
49 |
50 |
51 | def print_instance_statistics(instance):
52 |
53 | # Please note that many xbrl.Instance properties return generator objects
54 | # which cannot be used with len() directly
55 |
56 | print('Instance contains %d contexts' % sum(1 for _ in instance.contexts))
57 | print('Instance contains %d units' % sum(1 for _ in instance.units))
58 |
59 | # Print statistics about reported facts
60 | print('Instance contains %d facts' % len(instance.facts))
61 | print('Instance contains %d nil facts' % len(instance.nil_facts))
62 | print('Instance contains %d top-level item facts' %
63 | len(instance.child_items))
64 | print('Instance contains %d top-level tuple facts' %
65 | len(instance.child_tuples))
66 |
67 | facts_with_footnotes = 0
68 | for role in instance.footnote_link_roles():
69 | network = instance.footnote_base_set(role).network_of_relationships()
70 | facts_with_footnotes += sum(1 for _ in network.roots)
71 | print('Instance contains %d facts with attached footnotes' %
72 | facts_with_footnotes)
73 |
74 | # Print statistics about embedded footnotes
75 | footnotes = {}
76 | for footnote_link in instance.footnote_links:
77 | for footnote in footnote_link.resources:
78 | if footnote.xml_lang in footnotes:
79 | footnotes[footnote.xml_lang] += 1
80 | else:
81 | footnotes[footnote.xml_lang] = 1
82 | print('Instance contains %d footnote resources' % sum(footnotes.values()))
83 | for lang in footnotes.keys():
84 | print('Instance contains %d footnote resources in language %s' %
85 | (footnotes[lang], lang))
86 |
87 | # Main entry point, will be called by RaptorXML after the XBRL taxonomy
88 | # (DTS) validation job has finished
89 |
90 |
91 | def on_dts_finished(job, dts):
92 | # instance object will be None if validation was not successful
93 | if instance:
94 | print_dts_statistics(dts)
95 |
96 | # Main entry point, will be called by RaptorXML after the XBRL instance
97 | # validation job has finished
98 |
99 |
100 | def on_xbrl_finished(job, instance):
101 | # instance object will be None if validation was not successful
102 | if instance:
103 | print_dts_statistics(instance.dts)
104 | print_instance_statistics(instance)
105 |
--------------------------------------------------------------------------------
/presentation_linkbase_traversal.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script uses RaptorXML Python API v2 to print out all the presentation networks found in the DTS as simple trees
18 | #
19 | # Example invocation:
20 | # raptorxmlxbrl valxbrl --script=presentation_linkbase_traversal.py
21 | # nanonull.xbrl
22 |
23 | from altova import *
24 |
25 |
26 | def concept_label(concept, label_role=None):
27 | if not label_role:
28 | label_role = xbrl.taxonomy.ROLE_LABEL
29 | # Find all labels matching the given criteria
30 | labels = list(concept.labels(label_role=label_role, lang='en'))
31 | if not labels:
32 | # If not labels are found fallback to concept QName
33 | return str(concept.qname)
34 | # Return text of first label found
35 | return labels[0].text
36 |
37 |
38 | def print_tree_level(network, concept, preferred_label_role=None, level=1):
39 | # Print label of concept
40 | print('\t' * level, concept_label(concept, preferred_label_role))
41 |
42 | # Iterate over all child concepts
43 | for rel in network.relationships_from(concept):
44 | # Recurse for each child concept considering the preferredLabel
45 | # attribute on the presentationArcs
46 | print_tree_level(network, rel.target, rel.preferred_label, level + 1)
47 |
48 |
49 | def linkrole_definition(dts, linkrole):
50 | try:
51 | # Return the human readable roleType definition string for the given
52 | # linkrole if present
53 | return dts.role_type(linkrole).definition.value
54 | except:
55 | # Otherwise just return the linkrole URI
56 | return linkrole
57 |
58 |
59 | def print_presentation_tree(dts, linkrole):
60 | print(linkrole_definition(dts, linkrole))
61 |
62 | # Get the effective network of presentation relationships for the given
63 | # linkrole URI
64 | network = dts.presentation_base_set(linkrole).network_of_relationships()
65 |
66 | # Iterate over all root concepts
67 | for root in network.roots:
68 | print_tree_level(network, root)
69 |
70 |
71 | def print_presentation_linkbase(dts):
72 | # Iterate over all presentation extended link roles
73 | for linkrole in dts.presentation_link_roles():
74 | print_presentation_tree(dts, linkrole)
75 |
76 | # Main entry point, will be called by RaptorXML after the XBRL taxonomy
77 | # (DTS) validation job has finished
78 |
79 |
80 | def on_dts_finished(job, dts):
81 | # dts object will be None if validation was not successful
82 | if dts:
83 | print_presentation_linkbase(dts)
84 |
85 | # Main entry point, will be called by RaptorXML after the XBRL instance
86 | # validation job has finished
87 |
88 |
89 | def on_xbrl_finished(job, instance):
90 | # instance object will be None if validation was not successful
91 | if instance:
92 | print_presentation_linkbase(instance.dts)
93 |
--------------------------------------------------------------------------------
/script_parameters.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script demonstrates how to supply additional parameters to RaptorXML Python API v2 scripts.
18 | # To specify one or more script parameters on the command line, use the --script-param="key:value" option.
19 | # To specify one or more script parameters in XMLSpy, edit the "Script Parameters" field in the RaptorXML Server Options dialog.
20 | #
21 | # Example invocation:
22 | # raptorxml valxml-withxsd --streaming=false --script=script_parameters.py
23 | # --script-param="mystring:Lorem ipsum" --script-param="myint:99"
24 | # --script-param="foo:bar" ExpReport.xml
25 |
26 | from altova import *
27 |
28 |
29 | def print_params(params):
30 | # Print out all supplied script parameters
31 | for key, value in params.items():
32 | print(key, '=', value)
33 |
34 | # Access some specific parameters (using predefined defaults if parameter
35 | # was not specified)
36 | mystring = params.get('mystring', 'hello world')
37 | # Manually cast to int, as script parameters are always represented as
38 | # strings
39 | myint = int(params.get('myint', 42))
40 | print('mystring =', mystring)
41 | print('myint =', myint)
42 |
43 | # Main entry point, will be called by RaptorXML after the XML instance
44 | # validation job has finished
45 |
46 |
47 | def on_xsi_finished(job, instance):
48 | print_params(job.script_params)
49 |
50 | # Main entry point, will be called by RaptorXML after the XBRL instance
51 | # validation job has finished
52 |
53 |
54 | def on_xbrl_finished(job, instance):
55 | print_params(job.script_params)
56 |
--------------------------------------------------------------------------------
/write_to_file.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This RaptorXML Python API v2 script demonstrates how to generate additional output files.
18 | #
19 | # Example invocation:
20 | # raptorxml valxml-withxsd --streaming=false --script=write_to_file.py
21 | # ExpReport.xml
22 |
23 | import builtins
24 | import os
25 | from altova import *
26 |
27 |
28 | def write_to_file(job, instance):
29 | # Create a new file in the job output directory
30 | filepath = os.path.join(job.output_dir, 'my_script_output.txt')
31 | with builtins.open(filepath, mode='w', encoding='utf-8') as f:
32 | # Use the instance object and write any generated content to f
33 | # For example, lets output the name of the root element
34 |
35 | # instance object will be None if XML validation was not successful
36 | if instance:
37 | f.write('The root element is <' +
38 | instance.document_element.local_name + '>')
39 | else:
40 | f.write('XML instance is not valid')
41 |
42 | # Register new output file with RaptorXML engine
43 | job.append_output_filename(filepath)
44 |
45 | # This entry point will be called by RaptorXML after the XML instance
46 | # validation job (valxml-withxsd) has finished
47 |
48 |
49 | def on_xsi_finished(job, instance):
50 | write_to_file(job, instance)
51 |
52 | # Main entry point, will be called by RaptorXML after the XBRL instance
53 | # validation job has finished
54 |
55 |
56 | def on_xbrl_finished(job, instance):
57 | write_to_file(job, instance)
58 |
--------------------------------------------------------------------------------
/xml_pretty_print.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script uses RaptorXML Python API v2 to demonstrate how to create a pretty printed text representation of the XML DOM.
18 | #
19 | # Example invocation:
20 | # raptorxml valxml-withxsd --streaming=false --script=xml_pretty_print.py
21 | # ExpReport.xml
22 |
23 | from altova import xml
24 | import builtins
25 | import os.path
26 |
27 |
28 | def _pretty_print(node, output, depth=0):
29 |
30 | if isinstance(node, xml.ElementInformationItem):
31 | start_tag = []
32 | start_tag.append('%s<' % (' ' * depth * 3))
33 | if node.prefix:
34 | start_tag.append('%s:' % node.prefix)
35 | start_tag.append(node.local_name)
36 |
37 | for attr in node.namespace_attributes:
38 | start_tag.append(' ')
39 | if attr.prefix:
40 | start_tag.append('%s:' % attr.prefix)
41 | start_tag.append('%s="%s"' %
42 | (attr.local_name, attr.normalized_value))
43 |
44 | for attr in node.attributes:
45 | start_tag.append(' ')
46 | if attr.prefix:
47 | start_tag.append('%s:' % attr.prefix)
48 | start_tag.append('%s="%s"' %
49 | (attr.local_name, attr.normalized_value))
50 |
51 | if next(node.children, None) is None:
52 | # Empty element tag
53 | start_tag.append('/>')
54 | output.append(''.join(start_tag))
55 |
56 | else:
57 | start_tag.append('>')
58 | output.append(''.join(start_tag))
59 |
60 | for child in node.children:
61 | _pretty_print(child, output, depth + 1)
62 |
63 | end_tag = []
64 | end_tag.append('%s' % (' ' * depth * 3))
65 | if node.prefix:
66 | end_tag.append('%s:' % node.prefix)
67 | end_tag.append('%s>' % node.local_name)
68 | output.append(''.join(end_tag))
69 |
70 | elif isinstance(node, xml.CharDataInformationItem):
71 | if not node.element_content_whitespace:
72 | output.append('%s%s' % (
73 | ' ' * depth * 3, node.value.replace('&', '&').replace('<', '>')))
74 |
75 | elif isinstance(node, xml.CommentInformationItem):
76 | output.append('%s' % (' ' * depth * 3, node.content))
77 |
78 | elif isinstance(node, xml.ProcessingInstructionInformationItem):
79 | xmlpi = []
80 | xmlpi.append('%s%s' % (' ' * depth * 3, node.target))
81 | if node.content:
82 | xmlpi.append(' %s' % node.content)
83 | xmlpi.append('?>')
84 | output.append(''.join(xmlpi))
85 |
86 | elif isinstance(node, xml.DocumentInformationItem):
87 | xml_decl = []
88 | xml_decl.append('%s')
95 | output.append(''.join(xml_decl))
96 |
97 | for child in node.children:
98 | _pretty_print(child, output, depth)
99 |
100 | elif isinstance(node, xml.Document):
101 | _pretty_print(node.document, output, depth)
102 |
103 |
104 | def pretty_print(node, depth=0):
105 | """Return a pretty printed text representation of the XML DOM."""
106 |
107 | output = []
108 | _pretty_print(node, output, depth)
109 | return '\n'.join(output)
110 |
111 |
112 | def generate_output(job, instance):
113 | """Save the XML DOM to as a pretty printed XML text file."""
114 |
115 | # Create a new file in the job output directory
116 | filepath = os.path.join(job.output_dir, 'output.xml')
117 | with builtins.open(filepath, mode='w', encoding='utf-8') as f:
118 | f.write(pretty_print(instance.document))
119 |
120 | # Register new output file with RaptorXML engine
121 | job.append_output_filename(filepath)
122 |
123 | # Main entry point, will be called by RaptorXML after the XML instance
124 | # validation job has finished
125 |
126 |
127 | def on_xsi_finished(job, instance):
128 | # instance object will be None if XML Schema validation was not successful
129 | if instance:
130 | generate_output(job, instance)
131 |
132 | # Main entry point, will be called by RaptorXML after the XBRL instance
133 | # validation job has finished
134 |
135 |
136 | def on_xbrl_finished(job, instance):
137 | # instance object will be None if XBRL 2.1 validation was not successful
138 | if instance:
139 | generate_output(job, instance)
140 |
--------------------------------------------------------------------------------
/xml_traversal.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015, 2016 Altova GmbH
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | __copyright__ = "Copyright 2015, 2016 Altova GmbH"
15 | __license__ = 'http://www.apache.org/licenses/LICENSE-2.0'
16 |
17 | # This script uses RaptorXML Python API v2 to demonstrate how to navigate through an XML Infoset tree.
18 | #
19 | # Example invocation:
20 | # raptorxml valxml-withxsd --streaming=false --script=xml_traversal.py
21 | # ExpReport.xml
22 |
23 | from altova import *
24 |
25 |
26 | def print_character(char, depth):
27 | # Ignore whitespace
28 | if not char.element_content_whitespace:
29 | # Please note that multiple characters are merged into a single string
30 | print("\t" * depth, 'CDATA', char.value)
31 |
32 |
33 | def print_comment(comment, depth):
34 | print("\t" * depth, 'COMMENT', comment.content)
35 |
36 |
37 | def print_pi(pi, depth):
38 | print("\t" * depth, 'PROCESSING INSTRUCTION', pi.target, pi.content)
39 |
40 |
41 | def print_attribute(attr, depth):
42 | print("\t" * depth, 'ATTRIBUTE',
43 | '{%s}:%s' % (attr.namespace_name, attr.local_name), attr.normalized_value)
44 |
45 |
46 | def print_element(elem, depth):
47 | print("\t" * depth, 'ELEMENT', '{%s}:%s' %
48 | (elem.namespace_name, elem.local_name))
49 |
50 | # Print attributes
51 | for attr in elem.attributes:
52 | print_attribute(attr, depth + 1)
53 | # Print element content
54 | for child in elem.children:
55 | print_item(child, depth + 1)
56 |
57 |
58 | def print_item(item, depth=1):
59 | if isinstance(item, xml.ElementInformationItem):
60 | print_element(item, depth)
61 | elif isinstance(item, xml.CharDataInformationItem):
62 | print_character(item, depth)
63 | elif isinstance(item, xml.CommentInformationItem):
64 | print_comment(item, depth)
65 | elif isinstance(item, xml.ProcessingInstructionInformationItem):
66 | print_pi(item, depth)
67 |
68 |
69 | def print_document(doc):
70 | print('DOCUMENT', doc.base_uri)
71 | for child in doc.children:
72 | print_item(child)
73 |
74 | # Main entry point, will be called by RaptorXML after the XML instance
75 | # validation job has finished
76 |
77 |
78 | def on_xsi_finished(job, instance):
79 | # instance object will be None if XML Schema validation was not successful
80 | if instance:
81 | print_document(instance.document)
82 |
83 | # Main entry point, will be called by RaptorXML after the XBRL instance
84 | # validation job has finished
85 |
86 |
87 | def on_xbrl_finished(job, instance):
88 | # instance object will be None if XBRL 2.1 validation was not successful
89 | if instance:
90 | print_document(instance.document)
91 |
--------------------------------------------------------------------------------
/xpath_xquery_xslt_py/README.md:
--------------------------------------------------------------------------------
1 | # RaptorXML-Examples using the xpath api in Python #
2 |
3 | Examples for using the [Python API](https://www.altova.com/manual/en/raptorapi/pyapiv2/2.10.0/html/index.html) of [RaptorXML+XBRL Server](https://www.altova.com/raptorxml).
4 |
5 | ##### INTRO.md
6 | * a quick intro tutorial on the usage of the xpath, xquery and xslt engines in the python environment
7 |
8 | ##### xslt_demo_sample.py
9 | * an example demonstrating how to set-up a session, compile and execute an xslt stylesheet, with callback extension functions to the python environment
10 |
--------------------------------------------------------------------------------