Adding Child Element to XML using Linq-To-XML - c#

Here is how the XML is being created (using .Net 4.7):
public XElement ConstructHvtPayload(PayPageRequest ppRequest)
{
XNamespace xNamespace = "http://www.litle.com/schema";
var request =
new XElement(xNamespace + "litleRequest",
new XAttribute("version", "9.13"),
new XAttribute("xmlns", "http://www.litle.com/schema"),
new XAttribute("id", OrderId),
new XAttribute("numBatchRequests", "1"),
new XElement(xNamespace + "authentication",
new XElement(xNamespace + "user", "testuser"),
new XElement(xNamespace + "password", "winteriscoming")),
new XElement(xNamespace + "batchRequest",
new XAttribute("id", OrderId),
new XAttribute("numTokenRegistrations", "1"),
new XAttribute("merchantId", MerchantId),
new XElement(xNamespace + "registerTokenRequest" ,
new XAttribute("id", OrderId), right?
new XAttribute("reportGroup", MerchantId),
new XElement(xNamespace + "orderId", ppRequest.OrderId),
new XElement(xNamespace + "accountNumber", ppRequest.AccountNumber)
)));
return request;
}
What I want to do is add a If statement before the return to insert a new element "cardValidationNumber" if a particular condition is met.
I have tried the following (and other similar options):
request.Element("batchRequest").Element("tokenRequest").Add(new XElement(xNamespace + "cardValidationNum", "CCV"));
and I am getting Object instance not set errors. I have also tried the following format:
request.Root......(But Root is not available as an option)
What am I missing? I suspect from the current replies it might be something to do with the custom namespace I am using??
Thanks.

Without knowing where "request" is coming from, it's hard to pinpoint why you are getting errors.
Assuming request is the XDocument itself, it should look like this
request.Element("littleRequest").Element("batchRequest").Element("tokenRequest").Add(new XElement("ccv", "NEW ELEMENT & VALUE HERE"));

Try this:
var doc = XElement.Parse("<littleRequest><authentication><user>USER NAME HERE</user><password>PASSWORD HERE</password></authentication><batchRequest><tokenRequest><orderId>ORDER ID VALUE</orderId><accountNumber>accountNumberHERE</accountNumber></tokenRequest></batchRequest></littleRequest>");
var tokenRequest = doc.Descendants("tokenRequest").FirstOrDefault();
tokenRequest?.Add(new XElement("ccv", "NEW ELEMENT & VALUE HERE"));
string xml = doc.ToString();
It works for me.

Try like this(using XPath not LINQ to XML though)
string path = #"D:\testing.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
string item = "abcxyz";
XmlElement el = (XmlElement)doc.SelectSingleNode("//tokenRequest");
if (el != null)
{
XmlElement elem = doc.CreateElement("CCV");
elem.InnerText = item;
el.AppendChild(elem);
}
doc.Save(path);

Related

XElement with LINQ add node after specific node

I've got this XML:
<?xml version="1.0" encoding="utf-8"?>
<JMF SenderID="InkZone-Controller" Version="1.2">
<Command ID="cmd.00695" Type="Resource">
<ResourceCmdParams ResourceName="InkZoneProfile" JobID="K_41">
<InkZoneProfile ID="r0013" Class="Parameter" Locked="false" Status="Available" PartIDKeys="SignatureName SheetName Side Separation" DescriptiveName="Schieberwerte von DI" ZoneWidth="32">
<InkZoneProfile SignatureName="SIG1">
<InkZoneProfile Locked="False" SheetName="S1">
<InkZoneProfile Side="Front">
<ColorPool Class="Parameter" DescriptiveName="Colors for the job" Status="Available">
<InkZoneProfile Separation="PANTONE 647 C" ZoneSettingsX="0 0,003 " />
</ColorPool>
</InkZoneProfile>
</InkZoneProfile>
</InkZoneProfile>
</InkZoneProfile>
</ResourceCmdParams>
</Command>
</JMF>
I'm trying to add a node after a specific node() , using XElement and Linq. But my LINQ query always returns me null.
Tried this:
XElement InkZonePath = XmlDoc.Element("JMF").Elements("InkZoneProfile").Where(z => z.Element("InkZoneProfile").Attribute("Side").Value == "Front").SingleOrDefault();
And this:
XmlDoc.Element("JMF")
.Elements("InkZoneProfile").Where(InkZoneProfile => InkZoneProfile.Attribute("Side")
.Value == "Front").FirstOrDefault().AddAfterSelf(new XElement("InkZoneProfile",
new XAttribute("Separation", x.colorname),
new XAttribute("ZoneSettingsX", x.colorvalues)));
I've built this queries following those examples:
Select XElement where child element has a value
Insert XElements after a specific node
LINQ-to-XML XElement query NULL
But it didn't worked as expected. What is wrong with the LINQ Query ? From what i've read it should work (logically reading the expression i can understand it).
Thanks
EDIT-1: Entire writexml Method
public void writexml(xmldatalist XMLList, variables GlobalVars)
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = "\t",
NewLineChars = Environment.NewLine,
NewLineHandling = NewLineHandling.Replace,
Encoding = new UTF8Encoding(false)
};
string DesktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string FileExtension = ".xml";
string PathString = Path.Combine(DesktopFolder, "XML");
System.IO.Directory.CreateDirectory(PathString);
foreach (List<xmldata> i in XMLList.XMLArrayList)
{
int m = 0;
foreach (var x in i)
{
string XMLFilename = System.IO.Path.GetFileNameWithoutExtension(x.xml_filename);
GlobalVars.FullPath = Path.Combine(PathString, XMLFilename + FileExtension);
if (!File.Exists(GlobalVars.FullPath))
{
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("JMF",
new XAttribute("SenderID", "InkZone-Controller"),
new XAttribute("Version", "1.2"),
new XElement("Command",
new XAttribute("ID", "cmd.00695"),
new XAttribute("Type", "Resource"),
new XElement("ResourceCmdParams",
new XAttribute("ResourceName", "InkZoneProfile"),
new XAttribute("JobID", "K_41"),
new XElement("InkZoneProfile",
new XAttribute("ID", "r0013"),
new XAttribute("Class", "Parameter"),
new XAttribute("Locked", "False"),
new XAttribute("Status", "Available"),
new XAttribute("PartIDKeys", "SignatureName SheetName Side Separation"),
new XAttribute("DescriptiveName", "Schieberwerte von DI"),
new XAttribute("ZoneWidth", "32"),
new XElement("InkZoneProfile",
new XAttribute("SignatureName", "SIG1"),
new XElement("InkZoneProfile",
new XAttribute("Locked", "false"),
new XAttribute("SheetName", "S1"),
new XElement("InkZoneProfile",
new XAttribute("Side", "Front"),
new XElement("ColorPoolClass",
new XAttribute("Class", "Parameter"),
new XAttribute("DescriptiveName", "Colors for the job"),
new XAttribute("Status", "Available")
)))))))));
doc.Save(GlobalVars.FullPath);
XDocument XmlDoc = new XDocument();
XmlDoc = XDocument.Load(GlobalVars.FullPath);
XElement InkZonePath = XmlDoc.Root.Descendants("InkZoneProfile").Where(z => (string)z.Attribute("Side") == "Front").SingleOrDefault();
if (InkZonePath != null)
{
InkZonePath.AddAfterSelf(new XElement("InkZoneProfile",
new XAttribute("Separation", x.colorname),
new XAttribute("ZoneSettingsX", x.colorvalues)));
}
XmlDoc.Save(GlobalVars.FullPath);
}//Closing !FileExists
}//Closing inner foreach
}//Closing outer foreach
}//Closing writexml method
The problem with your current code is here : Element("JMF").Elements("InkZoneProfile") Since InkZoneProfile is not a direct child of JMF it will not return anything. Use Descendants instead.
Check difference between Elements & Descendants.
This should give you correct result:-
XElement InkZonePath = xdoc.Element("JMF").Descendants("InkZoneProfile")
.SingleOrDefault(z => (string)z.Attribute("Side") == "Front")
After this you can add whatever node you want to add using AddAfterSelf. Also note I have used SingleOrDefault here, but you may get exception if you have multiple matching nodes with this, In that case consider using FirstOrDefault.
Update:
To add new node:-
if (InkZonePath != null)
{
InkZonePath.AddAfterSelf(new XElement("InkZoneProfile",
new XAttribute("Separation", "Test"),
new XAttribute("ZoneSettingsX", "Test2")));
}
//Save XDocument
xdoc.Save(#"C:\Foo.xml");
You need to use Descendants method instead Elements:
XElement InkZonePath = XmlDoc.Root.Descendants("InkZoneProfile").Where(z => (string)z.Attribute("Side") == "Front").SingleOrDefault();
if(InkZonePath !=null)
InkZonePath.AddAfterSelf(new XElement("InkZoneProfile",
new XAttribute("Separation", x.colorname),
new XAttribute("ZoneSettingsX", x.colorvalues)));
you can use Descendants instead.
var node = XmlDoc.Descendants("InkZoneProfile").Where(x=> x.Attribute("Side") !=null && x.Attribute("Side").Value == "Front").FirstorDefault();

Adding attribute to XML Node always fail

I always get exception below when try to add attribute, why it's not working?
The prefix '' cannot be redefined from '' to 'http://ws.plimus.com'
within the same start element tag.
Code
var docXml = new XElement("param-encryption",
new XAttribute("xmlns", "http://ws.plimus.com"),
new XElement("parameters"));
var s = docXml.ToString();
I want to get result like
<param-encryption xmlns="http://ws.plimus.com">
<parameters>
</parameters>
</param-encryption>
This simplest approach is to let LINQ to XML do this automatically by specifying the namespace in the element name:
XNamespace ns = "http://ws.plimus.com";
var docXml = new XElement(ns + "param-encryption", new XElement(ns + "parameters"));
Result of docXml.ToString():
<param-encryption xmlns="http://ws.plimus.com">
<parameters />
</param-encryption>
Try this -
XNamespace aw = "http://ws.plimus.com";
XElement root = new XElement("param-encryption",
new XAttribute(XNamespace.Xmlns + "aw", "http://ws.plimus.com"),
new XElement("Child", "child content")
);
Console.WriteLine(root);
(EDIT):-
use this if you dont want namespace alias
XNamespace aw = "http://ws.plimus.com";
XElement root = new XElement(aw + "param-encryption",
new XAttribute("xmlns", "http://ws.plimus.com"),
new XElement( aw + "Child", "child content")
);

Creating XMLDocument throguh code in asp.net

am trying to generate an XML document like this through code.
<TestRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:2292/RMSchema.xsd">
<Version>3</Version>
<ApplicationHeader>
<AppLanguage />
<UserId>rmservice</UserId>
</ApplicationHeader>
<CustomerData>
<ExistingCustomerData>
<MTN>2084127182</MTN>
</ExistingCustomerData>
</CustomerData>
</TestRequest>
I tried some samples. But they create xmlns for the children, which i dont need. Any help is really appreciated.
I have tried the below code. But it is adding only xmlns to all children, which i dont need
XmlDocument xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
XmlElement xRoot = xDocument.CreateElement("TestRequest", "XNamespace.Xmlns=http://www.w3.org/2001/XMLSchema-instance" + " xsi:noNamespaceSchemaLocation=" + "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = 1;
Thanks
Tutu
I have tried with
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
XmlElement xRoot = xDocument.CreateElement("xsi","RMRequest",xsi);
xRoot.SetAttribute("noNamespaceSchemaLocation", xsi, "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
Now the response is
<?xml version=\"1.0\" encoding=\"windows-1252\"?><xsi:TestRequest xsi:noNamespaceSchemaLocation=\"http://localhost:2292/RMSchema.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
Here is the awesome LINQ to XML. Enjoy!
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(new XDeclaration("1.0", "windows-1252", null),
new XElement("TestRequest",
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "noNamespaceSchemaLocation", "http://localhost:2292/RMSchema.xsd"),
new XElement("Version",
new XText("3")
),
new XElement("ApplicationHeader",
new XElement("AppLanguage"),
new XElement("UserId",
new XText("rmservice")
)
),
new XElement("CustomerData",
new XElement("ExistingCustomerData",
new XElement("MTN",
new XText("2084127182")
)
)
)
)
);
doc.Save(filePath);
If you really want the old API, here it is:
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
var attr = xDocument.CreateAttribute("xsi", "noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
EDIT: From your comments, it looks like you want the xmlns:xsi and other attribute in that specific order. If so, you may have to trick the XmlDocument to add the xmlns:xsi attribute first.
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
// add namespace decl are attribute
var attr = xDocument.CreateAttribute("xmlns:xsi");
attr.Value = xsi;
xRoot.Attributes.Append(attr);
// no need to specify prefix, XmlDocument will figure it now
attr = xDocument.CreateAttribute("noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
Are you looking for something like this:-
XmlDocument xmldoc = new XmlDocument();
XmlNode root = xmldoc.AppendChild(xmldoc.CreateElement("Root"));
XmlNode child = root.AppendChild(xmldoc.CreateElement("Child"));
XmlAttribute childAtt =child.Attributes.Append(xmldoc.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "My node Innertext";
xmldoc.Save("ABC.xml");

Add xml namespace to XDocument

the output the i need is
<ns1:collection>
<ns1:child1>value1</ns1:child3>
<ns1:child2>value2</ns1:child3>
<ns1:child3>value3</ns1:child3>
</ns1:collection>
i try to do it by the code below - but i get an exception -...
How to add the namespace on this one ??
XDocument xDoc = new XDocument( new XElement( "collection",
new XElement( "ns1:child1", value1 ),
new XElement( "ns1:child2", value2 ),
new XElement( "ns1:child3", value3 ) ) );
I also try to use the
XNamespace ns1 = "http://url/for/ns1";";
and to do
( ns1 + "child1", value1 )
And still nothing
Move namespace declaration to the fictional parent element:
XDocument xDoc = new XDocument(new XElement("root",
new XAttribute(XNamespace.Xmlns + "ns1", ns1),
new XElement(ns1 + "collection",
new XElement(ns1 + "child1", value1),
new XElement(ns1 + "child2", value2),
new XElement(ns1 + "child3", value3))));
XDocument xDoc = new XDocument(new XElement(ns1+"collection",
new XAttribute(XNamespace.Xmlns+"ns1",ns1),
new XElement(ns1+ "child1", value1),
new XElement(ns1+"child2", value2),
new XElement(ns1+"child3", value3)));

Extracting data from a complex XML with LINQ

My goal is to save the data contained in the ValueReference node, TimeInstant attribute, and timePosition node into variables. I am able to get the value of the valueReference node (the un-commented section works), but not the other two.
Any help would be greatly appreciated.
Here is the code that I am working on:
public void LinqToXml()
{
XNamespace sosNamespace = XNamespace.Get("http://www.opengis.net/sos/2.0");
XNamespace fesNamespace = XNamespace.Get("http://www.opengis.net/fes/2.0");
XNamespace gmlNamespace = XNamespace.Get("http://www.opengis.net/gml/2.0");
var root = XElement.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var a = (from level in root.Descendants(sosNamespace + "temporalFilter")
select new
{
valueReference = (string)level.Descendants(fesNamespace + "After")
.Elements(fesNamespace + "ValueReference")
.First(),
/*timeInstant = (string)level.Descendants(fesNamespace + "After")
.Elements(gmlNamespace + "TimeInstant")
.Attributes(gmlNamespace + "id")
.First()*/
/*timePosition = (string)level.Descendants(fesNamespace + "After")
.Elements(gmlNamespace + "TimeInstant")
.First()*/
}).ToList();
And here is the XML I am trying to read:
<?xml version="1.0" encoding="UTF-8"?>
<sos:GetObservation xmlns="http://www.opengis.net/sos/2.0" service="SOS" version="2.0.0"
xmlns:sos="http://www.opengis.net/sos/2.0" xmlns:fes="http://www.opengis.net/fes/2.0"
xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:swe="http://www.opengis.net/swe/2.0"
xmlns:swes="http://www.opengis.net/swes/2.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sos/2.0
http://schemas.opengis.net/sos/2.0/sos.xsd">
<!--identifier of an offering-->
<offering>HG.Logger#DJK001</offering>
<!--identifier of an observed property-->
<observedProperty>HG</observedProperty>
<!--optional temporal filter restricting the results which shall be returned-->
<temporalFilter>
<fes:After>
<fes:ValueReference>phenomenonTime</fes:ValueReference>
<gml:TimeInstant gml:id="startPosition">
<gml:timePosition>2008-03-01T17:44:15.000+00:00</gml:timePosition>
</gml:TimeInstant>
</fes:After>
</temporalFilter>
<featureOfInterest>DJK001</featureOfInterest>
</sos:GetObservation>
Your gml namespace is not correct, after changing it to
XNamespace gmlNamespace = XNamespace.Get("http://www.opengis.net/gml/3.2");
you can use
timeInstant = level.Descendants(fesNamespace + "After")
.First()
.Element(gmlNamespace + "TimeInstant")
.Attribute(gmlNamespace + "id")
.Value,
timePosition = level.Descendants(fesNamespace + "After")
.First()
.Element(gmlNamespace + "TimeInstant")
.Value
You should do it like this
XNamespace sosNamespace = "http://www.opengis.net/sos/2.0";
XNamespace fesNamespace = "http://www.opengis.net/fes/2.0";
XNamespace gmlNamespace = "http://www.opengis.net/gml/3.2";
//you had used 2.0 instead of 3.2
var root = XElement.Load(#"C:\WorkingDirectory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var yourList=root.Descendants(sosNamespace+"temporalFilter").Descendants(fesNamespace+"After").Select(x=>
new
{
ValueReference=x.Element(fesNamespace+"ValueReference").Value,
timeInstant=x.Element(gmlNamespace+"TimeInstant").Attribute(gmlNamespace+"id").Value,
timePosition=x.Element(gmlNamespace+"TimeInstant").Element(gmlNamespace+"timePosition").Value
}
);
yourList contains all the data
you can also use good old XPath
var doc = new XPathDocument("1.xml");
var nav = doc.CreateNavigator();
var mng = new XmlNamespaceManager(nav.NameTable);
mng.AddNamespace("sos", "http://www.opengis.net/sos/2.0");
mng.AddNamespace("fes", "http://www.opengis.net/fes/2.0");
mng.AddNamespace("gml", "http://www.opengis.net/gml/3.2");
var valueReference = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/fes:ValueReference[1]", mng).TypedValue;
var TimeInstant = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/gml:TimeInstant/#gml:id", mng).TypedValue;
var timePosition = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/gml:TimeInstant/gml:timePosition[1]", mng).TypedValue;
TRY THIS CODE:
XmlDocument xmlSnippet = new XmlDocument();
xmlSnippet.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
//Selects all the similar nodes by tag Name.......
XmlNodeList xmlSnippetNodes = xmlSnippet.GetElementsByTagName("fes:After");
//Checking if any any xmlSnippetNode has matched.
if (xmlSnippetNodes != null)
{
//Checks if the matched xmlSnippetNode that has fes:After attribute is not NULL
//Stores the value of the matched tag.
var valueReference= xmlSnippetNodes.Item(0).Value;
var timeInstance=xmlSnippetNodes.Item(1).Attributes["gml:id"].Value;
var timePosition =xmlSnippetNodes.Item(1).InnerXml.Name;
//Return True if updated correctly.
isUpdated = true;
}

Categories

Resources