I have a xml-file:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<level>
<node1 />
<node2 />
<node3 />
</level>
</root>
What is the simplest way to insert values in node1, node2, node3 ?
C#, Visual Studio 2005
Here you go:
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(#"
<root>
<level>
<node1 />
<node2 />
<node3 />
</level>
</root>");
XmlElement node1 = xmldoc.SelectSingleNode("/root/level/node1") as XmlElement;
if (node1 != null)
{
node1.InnerText = "something"; // if you want a text
node1.SetAttribute("attr", "value"); // if you want an attribute
node1.AppendChild(xmldoc.CreateElement("subnode1")); // if you want a subnode
}
//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlFile);
Credit goes to Padrino.
How to change XML Attribute
XElement t = XElement.Load("filePath");
t.Element("level").Element("node1").Value = "";
t.Element("level").Element("node2").Value = "";
t.Element("level").Element("node3").Value = "";
t.Save("filePath");
Use AppendChild method to inser a child inside a node.
yournode.AppendChild(ChildNode);
link text
Related
Please how can I get value of attribute Value of element StatusCode in this XML:
<LogoutResponse
ID="_f525259e-7e91-4282-9dc3-a0da65a4a17a"
Version="2.0"
IssueInstant="2021-05-17T15:41:55Z"
InResponseTo="_5089729f-5cc0-4a66-a3c1-e710cde92897"
Destination="https://idp.xyz/logout.aspx"
xmlns="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://abc.xyz/api</Issuer>
<Status>
<StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</Status>
</LogoutResponse>
Due to the namespaces, this gets a little messy:
var doc = new XmlDocument();
doc.LoadXml(#"<LogoutResponse
ID=""_f525259e-7e91-4282-9dc3-a0da65a4a17a""
Version=""2.0""
IssueInstant=""2021-05-17T15:41:55Z""
InResponseTo=""_5089729f-5cc0-4a66-a3c1-e710cde92897""
Destination=""https://idp.xyz/logout.aspx""
xmlns=""urn:oasis:names:tc:SAML:2.0:protocol"">
<Issuer xmlns=""urn:oasis:names:tc:SAML:2.0:assertion"">https://abc.xyz/api</Issuer>
<Status>
<StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" />
</Status>
</LogoutResponse>");
var ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("oasis", "urn:oasis:names:tc:SAML:2.0:protocol");
var attr = (XmlAttribute)doc.SelectSingleNode(
"/oasis:LogoutResponse/oasis:Status/oasis:StatusCode/#Value", ns);
System.Console.WriteLine(attr.Value);
You can try with XmlDocument.
Note: since you have a name space (xmlns ...) all elements in your xml
by default in name space. hence you are getting object reference
error. I have updated the code and .netfiddle. please have a look
var xml = #"<LogoutResponse
ID=""_f525259e-7e91-4282-9dc3-a0da65a4a17a""
Version=""2.0""
IssueInstant=""2021-05-17T15:41:55Z""
InResponseTo=""_5089729f-5cc0-4a66-a3c1-e710cde92897""
Destination=""https://idp.xyz/logout.aspx""
xmlns=""urn:oasis:names:tc:SAML:2.0:protocol"">
<Issuer xmlns=""urn:oasis:names:tc:SAML:2.0:assertion"">https://abc.xyz/api</Issuer>
<Status>
<StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" />
</Status>
</LogoutResponse>";
var doc = new System.Xml.XmlDocument();
doc.LoadXml(xml);
var nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("ns", "urn:oasis:names:tc:SAML:2.0:protocol");
var result = doc.SelectSingleNode("/ns:LogoutResponse/ns:Status/ns:StatusCode/#Value", nsManager).InnerText;
Console.WriteLine(result);
By using LINQ to XML API.
It is available in the .Net Framework since 2007.
c#
void Main()
{
XDocument xdoc = XDocument.Parse(#"<LogoutResponse xmlns='urn:oasis:names:tc:SAML:2.0:protocol'
Destination='https://idp.xyz/logout.aspx' ID='_f525259e-7e91-4282-9dc3-a0da65a4a17a'
InResponseTo='_5089729f-5cc0-4a66-a3c1-e710cde92897' IssueInstant='2021-05-17T15:41:55Z' Version='2.0'>
<Issuer xmlns='urn:oasis:names:tc:SAML:2.0:assertion'>https://abc.xyz/api</Issuer>
<Status>
<StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'></StatusCode>
</Status>
</LogoutResponse>");
XNamespace ns1 = "urn:oasis:names:tc:SAML:2.0:protocol";
string StatusCodeValue = xdoc.Descendants(ns1 + "StatusCode")
.Attributes("Value")
.FirstOrDefault()?.Value;
Console.WriteLine("StatusCodeValue='{0}'", StatusCodeValue);
}
Output
StatusCodeValue='urn:oasis:names:tc:SAML:2.0:status:Success'
I want to change the values of some Elements but my code isn't working.
I have this XML-File:
<?xml version="1.0" encoding="utf-8"?>
<data>
<application id="1">
<applicationName>Instagram</applicationName>
<username>test</username>
<password>123</password>
<info>test</info>
</application>
</data>
And this C# Code:
string applicationName = "Test";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Data.xml");
XmlNode node = xmlDoc.SelectSingleNode("/data/application[#id='1']/applicationName");
node.InnerText = applicationName;
xmlDoc.Save("Data.xml");
What is the correct code to change the applicationName in the XML-File?
Use LINQ and XDocument:
string applicationName = "Test";
XDocument xdocument = XDocument.Load("Data.xml");
var appName = xdocument.Elements("applicationName").Single();
appName.Value = applicationName;
xdocument.Save("Data.xml");
But you should add System.Xml.Linq to your using directives first.
My XML looks like this. I want to get "NGSPkgTrackingId"
I have to walk Node->Node->Attribute.
I need some help
<TrackingID>{06EB4234-8A65-4C28-AD45-DAC87B972437}</TrackingID>
<Documents>
<Details Weight="1.7950" ZIP="04011" ZIPPlus4="3103" >
<Identifier Qualifier="eVSBarcode" Value="4200401192458927004050120118829995" />
<Identifier Qualifier="REFERENCENUM" Value="301113159600798" />
<Identifier Qualifier="NGSPkgTrackingId" Value="00983482428">
</Details>
<Details Weight="3.3450" ZIP="04011" CountryCode="US" >
< Identifier Qualifier="eVSBarcode" Value="4200401192612927004646230017808858" />
<Identifier Qualifier="REFERENCENUM" Value="117913788" /> Default="true" />
</Details>
Thank you
Try looking up the msdn documentation on XmlDocument. As har07 pointed out, you can use SelectSingleNode(). Which you can reference here.
As for what the code could look like, assuming you just want to find the value associated with a given Identifier Qualifier, it could work like this:
public static string FindValue(string qualifier, string xml)
{
var value = string.Empty;
XmlDocument doc = new XmlDocument();
doc.Load(xml);
XmlNode root = doc.DocumentElement;
XmlNode identifier = root.SelectSingleNode(#"descendant::Details/Identifier [#Qualifier='" + qualifier +"']");
value = identifier.Attributes["Value"].Value;
return value;
}
We should be doing null reference checks, so I'll add them in
public static string FindValue(string qualifier, string xml)
{
var value = string.Empty;
XmlDocument doc = new XmlDocument();
doc.Load(xml);
XmlNode identifier = null;
XmlNode root = doc.DocumentElement;
if (root != null)
identifier = root.SelectSingleNode(#"descendant::Details/Identifier [#Qualifier='" + qualifier +"']");
if (identifier?.Attributes != null) value = identifier.Attributes["Value"].Value;
return value;
}
Assuming you have a valid xml like this
<?xml version="1.0" encoding="utf-8" ?>
<Documents>
<Details Weight="1.7950" ZIP="04011" ZIPPlus4="3103" >
<Identifier Qualifier="eVSBarcode" Value="4200401192458927004050120118829995" />
<Identifier Qualifier="REFERENCENUM" Value="301113159600798" />
<Identifier Qualifier="NGSPkgTrackingId" Value="00983482428"/>
</Details>
<Details Weight="3.3450" ZIP="04011" CountryCode="US">
<Identifier Qualifier="eVSBarcode" Value="4200401192612927004646230017808858" />
<Identifier Qualifier="REFERENCENUM" Value="117913788" /> Default="true" />
</Details>
</Documents>
Accessing the value "NGSPkgTrackingId" should be pretty straightforward using the below code
XmlDocument xmlDoc = new XmlDocument();
XmlReader reader = XmlReader.Create("C:/Users/.../documents.xml ");
xmlDoc.Load(reader);
XmlNodeList nodeList = xmlDoc.SelectNodes("/Documents").Item(0).ChildNodes;
string val = xmlDoc.DocumentElement.ChildNodes[0].LastChild.Attributes.Item(0).Value;
Console.WriteLine(val);
Alternatively, you can use selectNodes
var node2 =xmlDoc.DocumentElement.SelectNodes(".//Details/Identifier");
var ans1= node2.Item(2).Attributes["Qualifier"].Value;
Console.WriteLine(ans1);
Third Option
var value= xmlDoc.DocumentElement.SelectSingleNode("descendant::Details").LastChild.Attributes["Qualifier"].Value;
Console.WriteLine(value);
Using C# I have an XML file like
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account>
<name>Jani</name>
</Account>
</root>
and I also have a function to read the name node as:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("lib//user.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
label1.Text = name.ToString();
but I am getting index out of range error as:
Why is this happening?
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
node is your root node. Which looks like this:
<root>
How many attributes does it have? None, as it turns out. An attribute in XML is one of these bar="baz" things:
<foo bar="baz">
node.Attributes[0] refers to the first attribute. There is no first attribute, there's no second attribute -- you didn't use attributes in this XML at all. Hence, that's out of range. There's no first item in an empty collection.
What you want is an element named name, which is farther down inside your XML tree.
Probably this:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
And then you'll want to look at node.InnerText to get "Jani" out of it.
You are trying to read node.Attributes[0].Value but there is no attribtues in your sample XML file. Not sure of the exact syntax but it should probably be closer to node.Value
As mentioned by other answers, your current XML does not have attributes.
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
If your XML did have attributes
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
Then you could do this:
private void DoItAgain()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data2.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node["Account"].Attributes[0].Value;
}
My xml file:
<?xml version="1.0" encoding="utf-8"?>
<layout name="layout">
<section name="Header">
<placeholder name="headers" width="30" class="header">sam,pam</placeholder>
</section>
<section name="Content">
<placeholder name="RightA" width="55">location</placeholder>
</section>
</layout>
I want to replace whole node if its contain sam.Means if node contains sam I want to rewrite node:
<placeholder name="headers" width="4,5,91">sam,sam2,pam</placeholder>
instead of:
<placeholder name="headers" width="30" class="header">sam,pam</placeholder>
In c#:
XmlDocument doc = new XmlDocument();
string sFileName = #"FileNameWithPath";
doc.Load(sFileName );
foreach (XmlNode ....... )
{
//Need help hear how to loop and replace.
}
Thanks.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Path");
XmlNodeList nodeList = xmlDoc.SelectNodes("section") ;
foreach (XmlNode node in nodeList)
{
XmlNode childNode = node.SelectSingleNode("placeholder");
if (childNode.Value.Contains("sam"))
{
childNode.Value = "sam,pam,sam2";
childNode.Attributes["width"].Value = "4,5,91";
}
}
xmlDoc.Save("Path");
Try using an XDocument for better control over find and replace.
XDocument myDocument = XDocument.Load("path to my file");
foreach (XElement node in myDocument.Root.Descendants("placeholder"))
{
if (node.Value.Contains("same"))
{
XElement newNode = new XElement("placeholder");
newNode.Add(new XAttribute("header", node.Attribute("header").Value); // if you want to copy the current value
newNode.Add(new XAttribute("width", "some new value"));
node.ReplaceWith(newNode);
}
}