I have problem with add schema to xml document. I added a schema to
the document and returning ActionResult I get an xml document without
a schema.
I defined the schema and added individual elements which I later added to the Xml document
How can I fix this problem?
[HttpGet("ConvertJsonToXML")]
[Produces("application/xml")]
public ActionResult ConvertJsonToXML(int? idProjectTlcStairsHistory)
{
//Find ID
var result = _project.FindProjectResult(idProjectTlcStairsHistory);
// Find name project
var nameProject = _project.ProjectName(idProjectTlcStairsHistory);
// Change format on improve format
var fileName = _project.ReplaceInvalidChars(nameProject);
JObject o = JObject.Parse(result);
XmlDocument doc = new XmlDocument();
string value = o.ToString();
doc = JsonConvert.DeserializeXmlNode(value, "StairsCalculationsData");
XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
nameSpace.Add("xsd", "http://www.w3.org/2001/XMLSchema");
//Schema
XmlSchema schema = new XmlSchema();
schema.ElementFormDefault = XmlSchemaForm.Qualified;
schema.AttributeFormDefault = XmlSchemaForm.Unqualified;
schema.Version = "1.0";
schema.Namespaces = nameSpace;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(schema);
XmlSchemaElement element = new XmlSchemaElement();
element.Name = "SpiralStairs";
element.SchemaTypeName = new XmlQualifiedName("string",
"http://www.w3.org/2001/XMLSchema");
XmlAttribute attr = doc.CreateAttribute("myns:blah", "http://myns.com");
attr.Value = "my own attribute";
element.UnhandledAttributes = new XmlAttribute[] { attr };
schema.Items.Add(element);
doc.Schemas.Add(schema);
doc.Schemas.Add(schemaSet);
var file = XMLConvert.AddXmlDeclaration(doc);
doc.LoadXml(file);
doc.Save(#"C:\Projekty XML\" + fileName + ".xml");
return Ok(doc);
}
Result - the result he gets without a schematic
<?xml version="1.0" encoding="utf-8"?>
<StairsCalculationsData>
<centralPipeDiameter>150</centralPipeDiameter>
<leftTurn>false</leftTurn>
<rightTurn>true</rightTurn>
<stairsTurn>-1</stairsTurn>
<centralPipeHandrail>false</centralPipeHandrail>
<centralPipeHandrailRadius>120</centralPipeHandrailRadius>
<radius>1000</radius>
<walkingWidth>1185</walkingWidth>
<walkingLineRadius>1000</walkingLineRadius>
<secondWalkingLineRadius>0</secondWalkingLineRadius>
<isStandardRadius>true</isStandardRadius>
<isTlcStandard>true</isTlcStandard>
<maxStepHeight>240</maxStepHeight>
<selectedRadius>1300</selectedRadius>
<selectedStep />
<levels>
<levelNumber>0</levelNumber>
<landing>
<initialDirection>4</initialDirection>
<landingShape>0</landingShape>
<startEdgeHeight>100</startEdgeHeight>
<endEdgeHeight>100</endEdgeHeight>
<startLandingAngle>90</startLandingAngle>
<endLandingAngle>0</endLandingAngle>
<isLandingAngleProperly>true</isLandingAngleProperly>
<landingWidth>1570.7963267948965</landingWidth>
<landingAngle>90</landingAngle>
</landing>
<isLastLevel>false</isLastLevel>
<angleNextLevel>20</angleNextLevel>
<startFlightAngleFromNextLevel>0</startFlightAngleFromNextLevel>
<levelMessages />
<isStepWidthProperly>true</isStepWidthProperly>
<stepDeepInWalkingLine>347.3</stepDeepInWalkingLine>
<heightLevel>2750</heightLevel>
<isStepHeightProperly>false</isStepHeightProperly>
<stepHeight>114.58333333333333</stepHeight>
<rotationRange>1.2777777777777777</rotationRange>
<startFlightAngle>190</startFlightAngle>
<flightRotationRangeAngle>460</flightRotationRangeAngle>
<stepAngle>20</stepAngle>
<isStepsAmountProperly>true</isStepsAmountProperly>
<stepsAmount>24</stepsAmount>
<stepsPerTurn>18</stepsPerTurn>
<isAngleDiffProperly>true</isAngleDiffProperly>
<angleDiff>0</angleDiff>
<isConvinienceProperly>false</isConvinienceProperly>
<convinience>576.47</convinience>
<isFreeSpaceByHeliceProperly>false</isFreeSpaceByHeliceProperly>
<endFreeSpaceByHelice>1440.2</endFreeSpaceByHelice>
<isFreeSpaceProperly>false</isFreeSpaceProperly>
<endFreeSpace>1504.2</endFreeSpace>
<isFlightFreeSpaceProperly>false</isFlightFreeSpaceProperly>
<flightFreeSpace>1847.9</flightFreeSpace>
<isFreeSpaceAboveLandingsProperly>true</isFreeSpaceAboveLandingsProperly>
<freeSpaceAboveLandings>2800</freeSpaceAboveLandings>
</levels>
</StairsCalculationsData>
How add to xml information from schema?
Example:
<xsd:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element myns:blah="my own attribute" name="SpiralStairs" type="xsd:string" xmlns:myns="http://myns.com" />
</xsd:schema>
Related
I have an XML document with ISO-8859-1 encoding.
I can load the XML with XDOCUMENT, but i can't storage a specific node.
Can somebody help me with this?
The xml:
<?xml version="1.0" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<TERMEKADATOutput xmlns="http://xmlns.oracle.com/orawsv/PUPHAX/PUPHAXWS">
<RETURN>
<OBJTERMEKADAT>
<TTT>210037069</TTT>
<TK>OGYI-T-04617/05</TK>
</OBJTERMEKADAT>
</RETURN>
</TERMEKADATOutput>
</soap:Body>
</soap:Envelope>
And the code:
XDocument xmlDoc = null;
using (StreamReader oReader = new StreamReader(#"C:\Users\maruzsama\source\repos\EPPuphax\EPPuphax\asd.xml", Encoding.GetEncoding("ISO-8859-1")))
{
xmlDoc = XDocument.Load(oReader); //this working fine
var result = from q in xmlDoc.Descendants("OBJTERMEKADAT")
select new
{
asd = q.Element("TTT").Value
};
Console.ReadKey();
}
I need the data from the TTT node (210037069)
Try following changes :
XDocument xmlDoc = null;
using (StreamReader oReader = new StreamReader(#"C:\Users\maruzsama\source\repos\EPPuphax\EPPuphax\asd.xml", Encoding.GetEncoding("ISO-8859-1")))
{
xmlDoc = XDocument.Load(oReader); //this working fine
XElement TERMEKADATOutput = xmlDoc.Descendants().Where(x => x.Name.LocalName == "TERMEKADATOutput").First();
XNamespace ns = TERMEKADATOutput.GetDefaultNamespace();
var result = from q in TERMEKADATOutput.Descendants(ns + "OBJTERMEKADAT")
select new
{
asd = q.Element(ns + "TTT").Value
};
Console.ReadKey();
}
i create an XMLDocument:
`
XmlDocument doc = new XmlDocument();
XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
// -----------------------create root-----------------------------
XmlElement rootnode = doc.CreateElement( "BMECAT");
doc.InsertBefore(declaire, doc.DocumentElement);
doc.AppendChild(rootnode);
//Console.WriteLine(sb.ToString());
//get attribute for BmeCat
rootnode.SetAttribute("version", "2005");
XmlAttribute atr = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
atr.Value = "http://www.adlnet.org/xsd/adlcp_v1p3";
rootnode.SetAttributeNode(atr);
rootnode.Attributes.Append(atr);`
then i convert it to XDocument using the function below but i get a NameSpace changed like this
XDocument ToXDocument(XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
`
below the xml and the XDocument
<?xml version="1.0" encoding="utf-8"?>
<BMECAT version="2005" p1:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance">
<?xml version="1.0" encoding="utf-8"?>
<BMECAT version="2005" xsi:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
You need to explicitly add the xsi namespace declaration manually at the beginning of your element.
Nodes are processed in document order and the namespace declaration appears later after it is first used. It doesn't know to use xsi for the prefix until it's too late.
var doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
var root = (XmlElement)doc.AppendChild(doc.CreateElement("BMECAT"));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
root.SetAttribute("xmlns:xsi", xsi); //set the namespace now
root.SetAttribute("schemaLocation", xsi, "http://www.adlnet.org/xsd/adlcp_v1p3");
root.SetAttribute("version", "2005");
I have xml file like this test.xml:
<?xml version="1.0" encoding="utf-8" ?>
<Message>
<Item Name ="msg1" Status ="false"/>
<Item Name="msg2" Status="false"/>
</Message>
System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader(test.xml);
System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
xdoc.Load(test.xml);
var testreader = xdoc.DocumentElement.ChildNodes;
string name = string.Empty;
string value = string.Empty;
if (message.MsgType == 10005)
{
value = "true";
}
else if (message.MsgType == 10002)
{
value = "false";
}
foreach (var mychild in testreader)
{
var childatt = ((System.Xml.XmlElement)mychild);
name = childatt.Attributes["Name"].Value;
value = childatt.Attributes["Status"].Value;
}
What I have to do to following thing:
I have to save updated value in xml file with xmltestReader and xmldocument
I'm getting request from third client about messageID so I have to check it's exist in xml file or not (e.g get request for msg1 so I have to match it xml file it's there or not).
hope I'm clear with my question.
//Get Message
//txtsearch text u have to pass message Id
var xmlFilePath = Server.MapPath("Test.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/TableMessage/Message");
string msgID = "",msgname="";
foreach (XmlNode node in nodeList)
{
if (node.SelectSingleNode("Message_Details").InnerText == "True" && node.SelectSingleNode("Message_id").InnerText==txtsearchtext.Text)
{
msgID = node.SelectSingleNode("Message_id").InnerText;
msgname = node.SelectSingleNode("Message_name").InnerText;
}
}
//store Updated Xml in ur project xml
//get the information from end user and pass the value to correspoding fields
XmlDocument xmlEmloyeeDoc = new XmlDocument();
xmlEmloyeeDoc.Load(Server.MapPath("~/Test.xml"));
XmlElement ParentElement = xmlEmloyeeDoc.CreateElement("Message");
XmlElement ID = xmlEmloyeeDoc.CreateElement("Message_id");
ID.InnerText = "6";
XmlElement message = xmlEmloyeeDoc.CreateElement("Message_name");
message.InnerText = "Message6";
XmlElement Details = xmlEmloyeeDoc.CreateElement("Message_Details");
Details.InnerText = "True";
ParentElement.AppendChild(ID);
ParentElement.AppendChild(message);
ParentElement.AppendChild(Details);
xmlEmloyeeDoc.DocumentElement.AppendChild(ParentElement);
xmlEmloyeeDoc.Save(Server.MapPath("~/Test.xml"));
I hope that code will help u
you will customize ur xml file like this
<?xml version="1.0" encoding="utf-8"?>
<TableMessage>
<Message>
<Message_id>Message1</Message_id>
<Message_name>Message1</Message_name>
<Message_Details>True</Message_Details>
</Message>
<Message>
<Message_id>Message2</Message_id>
<Message_name>Message2</Message_name>
<Message_Details>True</Message_Details>
</Message>
<Message>
<Message_id>Message3</Message_id>
<Message_name>Message3</Message_name>
<Message_Details>False</Message_Details>
</Message>
</TableMessage>
This question already has answers here:
How can I make the xmlserializer only serialize plain xml?
(4 answers)
Closed 8 years ago.
This is what I did:
A Serializable class:
[Serializable()]
public class Ticket
{
public string CitationNumber { get; set; }
public decimal Amount { get; set; }
}
Then serialize a model into xml:
var model = cart.Citations
.Select(c => new Ticket(c.Number, c.Amount)).ToList();
var serializer = new XmlSerializer(typeof (List<Ticket>));
var sw = new StringWriter();
serializer.Serialize(sw, model);
return sw.ToString();
The output sw.ToString() is like
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfTicket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Ticket>
<CitationNumber>00092844</CitationNumber>
<Amount>20</Amount>
</Ticket>
</ArrayOfTicket>
Is there a way to customize the Serialize() output to remove those schema info like: <?xml version="1.0" encoding="utf-16"?> and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"?
And how can I change the root element ArrayOfTicket into something else?
Do I have control with those output?
You need a few xml tricks...
var serializer = new XmlSerializer(typeof(List<Ticket>));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
var sw = new StringWriter();
var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { OmitXmlDeclaration = true });
serializer.Serialize(xmlWriter, model, ns);
string xml = sw.ToString();
Output:
<ArrayOfTicket>
<Ticket>
<CitationNumber>a</CitationNumber>
<Amount>1</Amount>
</Ticket>
<Ticket>
<CitationNumber>b</CitationNumber>
<Amount>2</Amount>
</Ticket>
</ArrayOfTicket>
PS: I added Indent = true to XmlWriterSettings to get the above output
My xml will be like below
<Employee>
<Emp>
<Name id="1" link="/office1/manager"></Name>
<Name id="2" link="/office/sweeper"></Name>
<Name id="3" link="/office2/manager"></Name>
</Emp>
</Employee>
I want to get the "id" of the employees who contains string "manager" in "link"
Using linq to xml:
XDocument doc = XDocument.Load("XMLFilePath");
var selectors = from elements in doc.Elements("Employee").Elements("Emp").Elements("Name")
where elements.Attribute("link").Value.Contains("manager")
select elements;
string ids = string.Empty;
foreach (var element in selectors)
{
ids += element.Attribute("id").Value + ",";
}
Also, for loading from string you can use:
XDocument doc = XDocument.Parse(xmlString);
var xDoc = XDocument.Parse(xml); //XDocument.Load(filename)
var ids = xDoc.Descendants("Name")
.Where(n => n.Attribute("link").Value.Contains("/manager"))
.Select(n => n.Attribute("id").Value)
.ToList();
//SELECT THE VALUES FROM XML USING C#
<?xml version="1.0" encoding="iso-8859-1"?>
<CONFIG>
<UsersList>
<SystemName>DOTNET-PC</SystemName>
<UserName>KARTHIKEYAN</UserName>
<ImagePath>C:\Users\DEVELOPER\AppData\Roaming\Office Messenger\assets\insta.jpg</ImagePath>
<PhotoPath>C:\Users\DEVELOPER\AppData\Roaming\Office Messenger\assets\NoPhoto.png</PhotoPath>
<UserStatus>Available</UserStatus>
<CustomStatus>Available</CustomStatus>
<theme>FF8B0000</theme>
</UsersList>
</CONFIG> //XML DOCUMENT
//C#
DataSet ds = new DataSet();
try
{
ds.ReadXml("C:\\config.xml");
}
catch { };
if (ds.Tables.Count > 0)
{
var results = from myRow in ds.Tables[0].AsEnumerable() where myRow.Field<string> ("SystemName") == SystemInformation.ComputerName select myRow;//ds.Tables[0] is <CONFIG> tag //in where SystemName=My system name to select the values from xml
foreach (var cust in results)
{
string _myName = cust["UserName"].ToString();
string _myLogoPath = cust["ImagePath"].ToString();
string _customStatus = cust["CustomStatus"].ToString();
string _myPhotoPath = cust["PhotoPath"].ToString();
}
}
//CREATE XML FROM C#
XDocument xmlDoc = XDocument.Load("C:\\config.xml");
xmlDoc.Root.Add(new XElement("UsersList", new XElement("SystemName", SystemInformation.ComputerName), new XElement("UserName", SystemInformation.ComputerName), new XElement("ImagePath", _filesPath + "\\insta.jpg"), new XElement("PhotoPath", _filesPath + "\\NoPhoto.png"), new XElement("UserStatus", "Available"), new XElement("CustomStatus", "Available"), new XElement("theme", "000000")));
xmlDoc.Save("C:\\config.xml");