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>
Related
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>
I'm trying to read values from following xml (which is previously fetched from FTP):
<?xml version="1.0" encoding="utf-8"?>
<eventdata xmlns="http://www.demoweb.net/xml/eventdata" >
<site>
<sitelink>demotesting</sitelink>
<user>15101991</user>
<measurement>
<nodelink>012019120312064500</nodelink>
<containername>A1</containername>
<time>2020-04-30T11:25:35</time>
<value type="n_v_unitvalue">0.04</value>
<value type="n_v_unitvalue_diff">0.040</value>
</measurement>
<measurement>
<nodelink>012019120312064501</nodelink>
<containername>A2</containername>
<time>2020-04-30T11:25:35</time>
<value type="n_v_unitvalue">0.0</value>
<value type="n_v_unitvalue_diff">-0.001</value>
</measurement>
<measurement>
<nodelink>012019120312064502</nodelink>
<containername>A3</containername>
<time>2020-04-30T11:25:34</time>
<value type="n_v_unitvalue">0.0</value>
<value type="n_v_unitvalue_diff">0.000</value>
</measurement>
</site>
<createdate>2020-04-30T11:25:35</createdate>
</eventdata>
Before I start, file is sucessfully loaded into memory :)
As you can see root node is eventdata, and site is the node where all data is contained.
So basically I need to loop all measurement nodes and get the data.
I also were struggling to get out user node.. here's what I've tried so far:
using (StreamReader xml_reader = new StreamReader(xml_response.GetResponseStream()))
{
string xml = xml_reader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
XmlNodeList mainFileContent = xmldoc.SelectNodes("eventdata");
// XmlNodeList mainFileContent = xmldoc.SelectNodes("eventdata/site");
XmlElement root = xmldoc.DocumentElement;
if (mainFileContent != null)
{
foreach (XmlNode node in mainFileContent)
{
var user = node["user"].InnerText;
}
}
}
What I'm missing?
THANKS GUYS
CHEERS
Your eventdata node has own xmlns declaration, you should properly handle it using XmlNamespaceManager and select the nodes with x:eventdata/x:site XPath expression
var xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
var nsmgr = new XmlNamespaceManager(xmldoc.NameTable);
nsmgr.AddNamespace("x", xmldoc.DocumentElement.NamespaceURI);
var mainFileContent = xmldoc.SelectNodes("x:eventdata/x:site", nsmgr);
foreach (XmlNode node in mainFileContent)
{
var user = node["user"]?.InnerText;
}
Use below code to read measurement
using (StreamReader xml_reader = new StreamReader(xml_response.GetResponseStream()))
{
string xml = xml_reader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
var nsmgr = new XmlNamespaceManager(xmldoc.NameTable);
nsmgr.AddNamespace("ns", "http://www.demoweb.net/xml/eventdata");
XmlNodeList mainFileContent = xmldoc.SelectNodes("ns:eventdata/ns:site",nsmgr);
XmlElement root = xmldoc.DocumentElement;
if (mainFileContent != null)
{
foreach (XmlNode site in mainFileContent)
{
var user = site["user"].InnerText;
XmlNodeList measurements = site.SelectNodes("ns:measurement", nsmgr);
if (measurements != null)
{
foreach (XmlNode measurement in measurements)
{
var containername = measurement["containername"].InnerText;
var time = measurement["time"].InnerText;
XmlNodeList values = measurement.SelectNodes("ns:value", nsmgr);
if (values != null)
{
foreach (XmlNode value in values)
{
var type = value.Attributes["type"].Value;
var v2 = value.InnerText;
}
}
}
}
}
}
}
i have xml file like this
> <?xml version='1.0' ?>
<config>
<app>
<app version="1.1.0" />
> </app>
</config>
and i want to read attribute version from node app
without any loop like this
while(reader.read()) or foreach etc.
Thanks
XmlDocument document = new XmlDocument();
document.Load("D:/source.xml");
XmlNode appVersion1 = document.SelectSingleNode("//app[#version]/#version");
XmlNode appVersion2 = document["config"]["app"]["app"].Attributes["version"];
Console.WriteLine("{0}, {1}",
appVersion1.Value,
appVersion2.Value);
You can do it this way.
XmlDocument doc = new XmlDocument();
string str = "<config><app><app version=" + "\"1.1.0\"" + "/></app></config>";
doc.LoadXml(str);
var nodes = doc.GetElementsByTagName("app");
foreach (XmlNode node in nodes)
{
if (node.Attributes["version"] != null)
{
string version = node.Attributes["version"].Value;
}
}
And you need to this for loop cause you got two nodes with same name App.
If you have a single node with name App,
XmlDocument doc = new XmlDocument();
string str = "<config><app version=" + "\"1.1.0\"" + "/></config>";
doc.LoadXml(str);
var node = doc.SelectSingleNode("//app");
if (node.Attributes["version"] != null)
{
string version = node.Attributes["version"].Value;
Console.WriteLine(version);
}
You can use linq to do
string stringXml= "yourXml Here";
XElement xdoc = XElement.Parse(stringXml);
var result= xdoc.Descendants("app").FirstOrDefault(x=> x.Attribute("version") != null).attribute("version").Value;
or:
var result = xdoc.Descendants("app").Where(x => x.Attribute("version") != null)
.Select(x => new { Version = x.Value });
I have a question about updating data in current xml file.
For example I want to change Radius to "50"
XML file:
<?xml version="1.0" encoding="utf-8"?>
<Settings>
<Radius>25</Radius>
<Length>40</Length>
<Height>15</Height>
<Name>Oks</Name>
</Settings>
I can read these settings with this code:
public void GetSettings()
{
XmlDocument xml = new XmlDocument();
xml.Load(location);
XmlNodeList xnList = xml.SelectNodes("/Settings");
foreach (XmlNode xn in xnList)
{
tb_height.Text = xn["Height"].InnerText;
tb_lenght.Text = xn["Length"].InnerText;
tb_radius.Text = xn["Radius"].InnerText;
tb_name.Text = xn["Name"].InnerText;
}
}
Not really sure what you are trying to do.
but to save your file, you can simply:
xml.Save(PathToSaveTo);
Got it working with
public void SaveSettings()
{
XmlDocument xml = new XmlDocument();
xml.Load(location);
XmlNodeList xnList = xml.SelectNodes("/Settings");
XmlNode xn = xml.SelectNodes("/Settings").Item(0);
xn["Height"].InnerText = tb_height.Text;
xn["Length"].InnerText = tb_lenght.Text;
xn["Radius"].InnerText = tb_radius.Text;
xn["Name"].InnerText = tb_name.Text;
xml.Save(location);
}
I want to modify XML data given below:
<?xml version="1.0" encoding="utf-8"?>
<allitems>
<item ID="17997" quantity="three">
<available>Y</available>
<last_modified_price>300</last_modified_price>
<edition>2008<edition>
<item>
<item ID="18039" quantity="two">
<available>Y</available>
<last_modified_price>250</last_modified_price>
<edition>2010<edition>
<item>
</allitems>
all elements value should be modified as per set in runtime....
For this I used following code but data is not modified..please help me in getting solution.
XmlDocument modifydoc = new XmlDocument();
modifydoc.Load(#"E:\XMLapp\XMLstorageWEB\patrick\XMLFile1.xml");
var root = modifydoc.GetElementsByTagName("allitems")[0];
var oldelem = root.SelectSingleNode("item[#ID =" + txt_id.Text + "]");
var newelem = modifydoc.CreateElement("item");
root.ReplaceChild(newelem, oldelem);
while (oldelem.ChildNodes.Count != 0)
{
XmlElement available= modifydoc.CreateElement("available");
available.InnerText = ddl_available.SelectedItem.Text;
XmlElement last_modified_price= modifydoc.CreateElement("last_modified_price");
last_modified_price.InnerText = ddl_last_modified_price.SelectedItem.Text;
XmlElement edition= modifydoc.CreateElement("edition");
edition.InnerText = ddl_edition.SelectedItem.Text;
newelem.AppendChild(available);
newelem.AppendChild(last_modified_price);
newelem.AppendChild(edition);
modifydoc.DocumentElement.AppendChild(newelem);
}
while (oldelem.Attributes.Count != 0)
{
newelem.Attributes.Append(oldelem.Attributes[0]);
}
modifydoc.Save(#"E:\XMLapp\XMLstorageWEB\patrick\XMLFile1.xml");
please give me solution..
Not the cleanest way, to add and remove a XmlNode, but just fixing your code I think this is what you want
var txt_id = "17997";
XmlDocument modifydoc = new XmlDocument();
modifydoc.Load(#"c:\temp\so\1.xml");
var root = modifydoc.GetElementsByTagName("allitems")[0];
var oldelem = root.SelectSingleNode("item[#ID =" + txt_id + "]");
var newelem = modifydoc.CreateElement("item");
root.ReplaceChild(newelem, oldelem);
XmlElement available= modifydoc.CreateElement("available");
available.InnerText = "CambiameInnerText";
XmlElement last_modified_price= modifydoc.CreateElement("last_modified_price");
last_modified_price.InnerText = "LastModifed";
XmlElement edition= modifydoc.CreateElement("edition");
edition.InnerText = "SelectedItem";
newelem.AppendChild(available);
newelem.AppendChild(last_modified_price);
newelem.AppendChild(edition);
modifydoc.DocumentElement.AppendChild(newelem);
foreach (XmlAttribute attribute in oldelem.Attributes)
{
newelem.SetAttribute(attribute.Name, attribute.Value);
}
and your xml is not correct, at least the example
<?xml version="1.0" encoding="utf-8"?>
<allitems>
<item ID="17997" quantity="three">
<available>Y</available>
<last_modified_price>300</last_modified_price>
<edition>2008</edition>
</item>
<item ID="18039" quantity="two">
<available>Y</available>
<last_modified_price>250</last_modified_price>
<edition>2010</edition>
</item>
</allitems>
Here is the small and easy example , i use for change the connectionString value in my [web.config]. I hope it's can help you. So easy to adapt for your code ;-)
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load("myFullPathWebConfig.xml");
foreach (System.Xml.XmlNode node in myXmlDocument["configuration"]["connectionStrings"])
{
if (node.Name == "add")
{
if (node.Attributes.GetNamedItem("name").Value == "SCI2ConnectionString")
{
node.Attributes.GetNamedItem("connectionString").Value = connectionString;
}
}
}