Reputation: 85
i have a xml file like this:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Prowadzacy xmlns:ns0="http://test.com/xi/prowizja/CODO">
<LIFNR>test</LIFNR>
<NAME>test</NAME>
<SMTP_ADR>[email protected]</SMTP_ADR>
<CALC_RULE>M</CALC_RULE>
<STATIONS>
<NUMBER>test</NUMBER>
<LOCATION>test</LOCATION>
<KDATB>test</KDATB>
<KDATE/>
</STATIONS>
<STATIONS>
<NUMBER>test</NUMBER>
<LOCATION>test</LOCATION>
<KDATB>test</KDATB>
<KDATE>test</KDATE>
</STATIONS>
</ns0:Prowadzacy>
and xsd like this (I've post only header of xsd):
<xsd:schema targetNamespace="http://orlen.pl/xi/prowizja/CODO" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://orlen.pl/xi/prowizja/CODO">
<xsd:complexType name="Prowadzacy">
<xsd:sequence>
i need to validate XML with this xsd, I was trying to do it like this, and get error about no element "ns0:Prowadzacy", i think i need to remove this attribute (or namespace in validation)?
private static XNamespace xn = "http://orlen.pl/xi/prowizja/CODO";
schemaSet.Add(xn.ToString(), XmlReader.Create(new StringReader(xsd)));
can any help me?
Upvotes: 0
Views: 345
Reputation: 939
Define a method as below to validate xml.
public static bool ValidateXml(string schemaFilePath, string xmlFilePath)
{
bool isValidXml = true;
var doc = XDocument.Load(xmlFilePath);
var schemas = new XmlSchemaSet();
const string xn = "http://orlen.pl/xi/prowizja/CODO";
schemas.Add(xn, XmlReader.Create(schemaFilePath));
doc.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
isValidXml = false;
});
Console.WriteLine("doc {0}", isValidXml ? "validated" : "did not validate");
return isValidXml;
}
UPDATE: Please try with below xsd and xml. I have made Name as required.
XSD:
<xs:schema targetNamespace="http://orlen.pl/xi/prowizja/CODO" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://orlen.pl/xi/prowizja/CODO">
<xs:element name="LIFNR" type="xs:string"/>
<xs:element name="NAME" type="xs:string"/>
<xs:element name="SMTP_ADR" type="xs:string"/>
<xs:element name="CALC_RULE" type="xs:string"/>
<xs:element name="STATIONS">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="NUMBER"/>
<xs:element type="xs:string" name="LOCATION"/>
<xs:element type="xs:string" name="KDATB"/>
<xs:element type="xs:string" name="KDATE"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Prowadzacy xmlns:ns0="http://test.com/xi/prowizja/CODO">
<LIFNR>test</LIFNR>
<NAME>test</NAME>
<SMTP_ADR>[email protected]</SMTP_ADR>
<CALC_RULE>M</CALC_RULE>
<STATIONS>
<NUMBER>test</NUMBER>
<LOCATION>test</LOCATION>
<KDATB>test</KDATB>
<KDATE/>
</STATIONS>
<STATIONS>
<NUMBER>test</NUMBER>
<LOCATION>test</LOCATION>
<KDATB>test</KDATB>
<KDATE>test</KDATE>
</STATIONS>
</ns0:Prowadzacy>
Note: Now if you change namespace in xml, it will say "not valid".
Upvotes: 1