
Security News
npm Adopts OIDC for Trusted Publishing in CI/CD Workflows
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
xml-helper-ts
Advanced tools
A TypeScript library for XML parsing, validation with XSD schema, and XML/JSON conversion - built from scratch without external dependencies
A comprehensive TypeScript library for XML parsing, validation, and conversion built from scratch without external dependencies.
npm install
npm run build
import XmlHelper from './src/index';
const xmlHelper = new XmlHelper();
// Load XSD schema
const schemaErrors = xmlHelper.loadSchema(xsdContent);
if (schemaErrors.length === 0) {
console.log('Schema loaded successfully!');
}
// Validate XML
const validationErrors = xmlHelper.validateXml(xmlContent);
if (validationErrors.length === 0) {
console.log('XML is valid!');
}
// Convert XML to JSON
const result = xmlHelper.xmlToJson(xmlContent);
if (result.success) {
console.log('JSON:', result.data);
}
// Convert JSON to XML
const xmlString = xmlHelper.jsonToXml(jsonData, 'root');
console.log('XML:', xmlString);
The main class that provides all XML processing functionality.
loadSchema(xsdContent: string): ValidationError[]
Loads and parses an XSD schema for validation.
xsdContent
: The XSD schema content as a stringvalidateXml(xmlContent: string): ValidationError[]
Validates XML content against the loaded schema.
xmlContent
: The XML content to validatexmlToJson(xmlContent: string, options?: XmlToJsonOptions): XmlParseResult
Converts XML to JSON format.
xmlContent
: The XML content to convertoptions
: Optional conversion settingsjsonToXml(jsonData: any, rootElement?: string, options?: JsonToXmlOptions): string
Converts JSON data to XML format.
jsonData
: The JSON data to convertrootElement
: Optional root element nameoptions
: Optional conversion settingsparseXml(xmlContent: string): { node: XmlNode | null; errors: ValidationError[] }
Parses XML without schema validation.
xmlContent
: The XML content to parseValidationError
interface ValidationError {
line: number; // Line number where error occurred
column: number; // Column number where error occurred
message: string; // Error description
code: string; // Error code identifier
}
XmlToJsonOptions
interface XmlToJsonOptions {
preserveAttributes?: boolean; // Include XML attributes (default: true)
attributePrefix?: string; // Prefix for attributes (default: '@')
textKey?: string; // Key for text content (default: '#text')
ignoreNamespaces?: boolean; // Ignore XML namespaces (default: false)
}
JsonToXmlOptions
interface JsonToXmlOptions {
attributePrefix?: string; // Prefix for attributes (default: '@')
textKey?: string; // Key for text content (default: '#text')
rootElement?: string; // Root element name (default: 'root')
declaration?: boolean; // Include XML declaration (default: true)
indent?: string; // Indentation string (default: ' ')
}
const xsdSchema = `<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>`;
const xmlHelper = new XmlHelper();
const errors = xmlHelper.loadSchema(xsdSchema);
if (errors.length === 0) {
const validationErrors = xmlHelper.validateXml(`
<person>
<name>John Doe</name>
<age>30</age>
</person>
`);
console.log('Valid:', validationErrors.length === 0);
}
const xml = `
<library>
<book id="1" category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price>12.99</price>
</book>
</library>`;
const result = xmlHelper.xmlToJson(xml, {
preserveAttributes: true,
attributePrefix: '@'
});
// Result:
// {
// "library": {
// "book": {
// "@id": "1",
// "@category": "fiction",
// "title": "The Great Gatsby",
// "author": "F. Scott Fitzgerald",
// "price": 12.99
// }
// }
// }
const json = {
person: {
'@id': 'p1',
name: 'Jane Smith',
details: {
age: 25,
city: 'New York'
},
hobbies: ['reading', 'swimming']
}
};
const xml = xmlHelper.jsonToXml(json);
// Result:
// <?xml version="1.0" encoding="UTF-8"?>
// <person id="p1">
// <name>Jane Smith</name>
// <details>
// <age>25</age>
// <city>New York</city>
// </details>
// <hobbies>reading</hobbies>
// <hobbies>swimming</hobbies>
// </person>
The library provides detailed error information including:
Common error codes:
PARSE_ERROR
: XML parsing failedSCHEMA_ERROR
: XSD schema is invalidELEMENT_NOT_FOUND
: Required element missingINVALID_ATTRIBUTE_VALUE
: Attribute value doesn't match typeMIN_OCCURS_VIOLATION
: Element occurs fewer times than requiredMAX_OCCURS_VIOLATION
: Element occurs more times than allowedRun the test suite to see all functionality in action:
npm run build
npm test
The test file (src/test.ts
) demonstrates:
The library is organized into focused modules:
XmlParser
: Core XML parsing functionalityXsdParser
: XSD schema parsing and interpretationXmlValidator
: XML validation against XSD schemasXmlToJsonConverter
: XML to JSON transformationJsonToXmlConverter
: JSON to XML transformationXmlHelper
: Main facade class combining all functionalityMIT License - feel free to use in your projects!
This is a from-scratch implementation without external dependencies. Contributions are welcome for:
FAQs
A TypeScript library for XML parsing, validation with XSD schema, and XML/JSON conversion - built from scratch without external dependencies
The npm package xml-helper-ts receives a total of 4 weekly downloads. As such, xml-helper-ts popularity was classified as not popular.
We found that xml-helper-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
Research
/Security News
A RubyGems malware campaign used 60 malicious packages posing as automation tools to steal credentials from social media and marketing tool users.
Security News
The CNA Scorecard ranks CVE issuers by data completeness, revealing major gaps in patch info and software identifiers across thousands of vulnerabilities.