I have XML which is like:
<?xml version="1.0" encoding="utf-16"?>
<RootNodeName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" MyAttribute="7" xmlns="mylink">
<IsValid>false</IsValid>
<Name>some matrix</Name>
...Some more nodes...
</RootNodeName>
and code which is like:
var doc = XDocument.Parse(myXmlString);
Console.WriteLine(doc.Root.Element("Name"));
and console shows just an empty space since doc.Root.Element("Name") returns null =(
While I can find this Element among doc.Root.Elements() results.
doc.Root.Attribute("MyAttribute") gives correct result as well.
What is wrong with it/me?
The <Name> element is in the mylink namespace:
XNamespace mylink = "mylink";
Console.WriteLine(doc.Root.Element(mylink + "Name"));
Related
<?xml version="1.0"?>
<TextType IsKey="false" Name="XMLReport"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Providers
xmlns="Reporting"/>
<Sales
xmlns="Reporting"/>
<Value
xmlns="Reporting">
<?xml version="1.0" encoding="utf-8"?>
<TestReport>
<StudyUid>
<![CDATA[123]]>
</StudyUid>
<Modality>
<![CDATA[XYZ]]>
</Modality>
<StudyDate format="DICOM">123456</StudyDate>
<StudyTime format="DICOM">6789</StudyTime>
<AccessionNumber>
<![CDATA[123]]>
</AccessionNumber>
<StudyDescription>
<![CDATA[abc def]]>
</StudyDescription>
<OperatorName format="xyz">
<![CDATA[abc]]>
</OperatorName>
<PhysicianReadingStudy format="xyz">
<![CDATA[^^^^]]>
</PhysicianReadingStudy>
<InstitutionName>
<![CDATA[xyz]]>
</InstitutionName>
<HospitalName>
<![CDATA[Hospital Name]]>
</HospitalName>
<ReportSet>
<MyReport ID="1">
<ReportStatus>
<![CDATA[Done]]>
</ReportStatus>
</MyReport>
<MyReport ID="2">
<ReportStatus>
<![CDATA[Done]]>
</ReportStatus>
</MyReport>
<MyReport ID="3">
<ReportStatus>
<![CDATA[Initial]]>
</ReportStatus>
</MyReport>
</ReportSet>
<ReportImageSet />
<FetusSet />
</TestReport>
</Value>
<WhoSetMe xmlns="Reporting">NotSpecified
</WhoSetMe>
</TextType>
I want to parse the xml above in C# and check whether "ReportStatus" is "Done" for all the ReportStatus under MyReport/ReportSet. One more twist here is the xml contains one more xml starts at "Value" tag as in above example.It may contatin many ReportStatus tag under ReportSet tag. Can someone please help me?
// Can you try this? I tried to do it with LINQ to XML.
// I assume you have multiple <TestReport /> elements in <Value /> tag
// and var xelement is your xml variable
// First we get all TestReport elemnts
IEnumerable<XElement> allReports =
from el in xelement.Elements("TextType/Value/TestReport")
select el;
// From allReports we get all MyReport elemnts
IEnumerable<XElement> allMyReports =
from el in allReports.Elements("ReportSet/MyReport")
select el;
// From allReports we also get all MyReport elemnts with element ReportStatus value equals "Done"
IEnumerable<XElement> allDoneMyReports =
from el in allMyReports
where (string)el.Element("ReportStatus") == "Done"
select el;
// Now we compare allMyReport with allDoneMyReports
if (allMyReports.Count() == allDoneMyReports.Count())
{
//DO Somehing
}
Your XML document is invalid. You need to fix it before trying to parse it. The issue is that a document can only have one top-level element; you have 2 <TextType> and <Providers>.
Most of your elements are the namespace Reporting. You need to use it when referencing the element.
XNamespace ns = "Reporting";
var value = doc.Element("Value" + ns);
Update
Just use the namespace for each element
XNamespace ns = "Reporting";
var value = xelement.Elements("Value" + ns);
Another Update
The XML document is considered invalid because it has multiple XML declarations; there is no way to disable this. I suggest you pre-process the document to remove the extra declarations. Here's an example (https://dotnetfiddle.net/UnuAF6)
var xml = "<?xml version='1.0'?><a> <?xml version='1.0'?><b id='b' /></a>";
var doc = XDocument.Parse(xml.Replace(" <?xml version='1.0'?", " "));
var bs = doc.Descendants("b");
Console.WriteLine("{0} 'b' elements", bs.Count());
I have an xml as an value of an element inside a Main xml. I want to scrub off or delete a node within the inner xml. How do I achieve that ?
For removing a node in main xml I am doing
var result = doc.Descendants("node1").Where(x => x.Attribute("id").Value == "002");
if (result != null)
{
result.Remove();
}
Here is my XML :
<?xml version="1.0" encoding="utf-16"?>
<root>
<node1>id="001" version="1.0"</node1>
<node2>id="002" version="1.0"</node1>
<report>raw = "<response = "10"><innerxml><prod>date = "18082016" name="pqr"</prod><seg1>id="002" name = "sqs"</seg1></innerxml></response>"</report>
</root>
Your code is correct but your xml is not. the XML should be like:
<?xml version="1.0" encoding="utf-16"?>
<root>
<node1 id="001" version="1.0"></node1>
<node2 id="002" version="1.0"></node2>
</root>
I am to get the element value of Soap based retuned XML as below.
XML File:
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<SendToDSSResponse xmlns="http://tempuri.org/">
<SendToDSSResult>
<RC>0</RC>
<RCD></RCD>
<PCKT>
<IDNO>1212</IDNO>
<IDTYPE>051</IDTYPE>
<NOBOX>121216</NOBOX>
<NAME>James</NAME>
</PCKT>
</SendToDSSResult>
</SendToDSSResponse>
</soap:Body>
</soap:Envelope>
Now I want to get the values of IDNO, NoBox and Name. I am trying to use the following code below to get the values but it throws an Exception. What's the correct way to get the element values?
C# Code:
var xDoc = XDocument.Parse(cleanXml); //OR XDocument.Load(filename)
string Name = xDoc.Descendants("Name").First().Value;
I think you should add XNamespace and then you can read out the specific value from the nodes or tags under the node, try this demo in your ConsoleApplication:
XDocument doc = XDocument.Load("XMLFile1.xml");
var result = doc.Descendants(XNamespace.Get("http://tempuri.org/")+"NAME").First();
Console.WriteLine(result.Value);
Use Root property.
string name = xDoc.Root.Descendants("NAME").First().Value;
The XML (fragment):
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetXMLResponse xmlns="http://sitecore.net/visual/">
<GetXMLResult>
<sitecore xmlns="">
<status>ok</status>
The code (fragment):
XmlNamespaceManager nsManager = new XmlNamespaceManager(template.NameTable);
nsManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsManager.PushScope();
XmlNode sitecoreRoot = template.SelectSingleNode("/soap:Envelope/soap:Body/*[namespace-uri()='http://sitecore.net/visual/' and local-name()='GetXMLResponse']", nsManager);
string status = sitecoreRoot.SelectSingleNode("/GetXMLResult/sitecore/status").Value;
sitecoreRoot element returns the correct node. However the XPath to get the status always returns null, even though the siteCoreRoot.OuterXMl property shows the element is present.
The only thing I can think of is the line:
<sitecore xmlns="">
is throwing off the XPath
TIA
XmlNamespaceManager ns = new XmlNamespaceManager(cd.NameTable);
ns.AddNamespace("sp", "http://schemas.xmlsoap.org/soap/envelope/");
ns.AddNamespace("sc", "http://sitecore.net/visual/");
XmlNode sitecoreRoot = cd.SelectSingleNode("//sp:Envelope/sp:Body/sc:GetXMLResponse/sc:GetXMLResult/sitecore/status", ns);
var status = sitecoreRoot.InnerText;
May help you?
If you just want the status node, you can try this xml library and the following XPath.
XElement root = XElement.Load(file); // or .Parse(string)
XElement status = root.XPathElement("//status");
The library handles doing the namespace for you.
I have an xml document that has a structure like so:
<?xml version="1.0" encoding="iso-8859-1" ?>
- <newdataset xml="version="1.0" encoding="iso-8859-1"">
- <officelist>
<officeid>2</officeid>
<office>Office</office>
<region>BC</region>
I would like to have the office id = 2 to be its own element. Like so
<?xml version="1.0" encoding="iso-8859-1" ?>
<newdataset xml="version="1.0" encoding="iso-8859-1"">
<officelist>
<officeid id=2/>
<office>Office</office>
<region>BC</region>
</officeid>
</officelist>
</newdataset>
xmlDS += offices.GetXml();
xmlDS = xmlDS.Replace(#"xml:space=""preserve""", " ");
XmlDocument doc = new XmlDocument();
XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
doc.LoadXml(xmlDS);
doc.Save(Response.OutputStream);
That is my code so far... not sure how to set a child node to become a parent node
using XDocument made this a lot easier with Linq.