Sample code for 30+ languages & platforms
Java

Check if a MIME Part is XML

See more MIME Examples

Demonstrates the Chilkat Mime.IsXml method, which returns true only for text/xml or application/xml. It takes no arguments and applies to the current part.

Note: The file path is relative to the application's current working directory. Absolute paths may also be used. Supply the path to your own file.

Background: Identifying an XML part matters in machine-to-machine messaging — SOAP, EDI, structured data payloads — where you want to hand the body to an XML parser. Note it matches only the two canonical XML media types and not structured-suffix types like application/xhtml+xml, so check the exact type when those are relevant.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Mime;

public class ChilkatExample {

    public static void main(String[] args) {
        // Demonstrates the Mime.IsXml method, which returns whether the Content-Type is text/xml or application/xml.  It takes no arguments and applies to the current
        // part.  This example iterates the parts of a multipart message and reports which ones match.

        Mime mime = new Mime();
        try {
            mime.loadMimeFile("qa_data/multipart_message.eml");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        int n = mime.getNumParts();
        Mime part = new Mime();
        for (int i = 0; i < n; i++) {
            try {
                mime.partAt(i, part);
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            if (part.isXml()) {
                System.out.println("Part " + i + " (" + part.getContentType() + ") is XML.");
            }
        }
    }
}