I have xml fragment in an xml-File. The fragment has tags with namespace.
How can I read that xml fragment, which represent exactly an XElement element ?
<node id="n0::n0">
<data key="d6">
<y:ShapeNode>
<y:Geometry height="91.44" width="59.49119999999999" x="364.256180835285" y="-698.4404365079365"/>
<y:Fill color="#FFCC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="t" textColor="#000000" visible="true" width="48.677734375" x="5.406732812499968" y="4.0">MELEIN</y:NodeLabel>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="27.35546875" x="16.067865624999968" y="20.843814062500087">8,00<y:LabelModel>
<y:SmartNodeLabelModel distance="4.0"/>
</y:LabelModel>
<y:ModelParameter>
<y:SmartNodeLabelModelParameter labelRatioX="0.0" labelRatioY="-0.5" nodeRatioX="0.0" nodeRatioY="-0.2720492775317138" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
</y:ModelParameter>
</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
I tried a lot of different ways the last one nearly comes to the target
var mngr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
mngr.AddNamespace(string.Empty, "urn: ignore"); // or proper URL
mngr.AddNamespace("y", "urn:ignore"); // or proper URL
var parserContext = new System.Xml.XmlParserContext(null, mngr, null, System.Xml.XmlSpace.None, null);
var txtReader = new System.Xml.XmlTextReader("block.graphml", System.Xml.XmlNodeType.Element, parserContext);
var ele = XElement.Load(txtReader);
but it crashes in the last line with System.InvalidOperationException
Is there any easy way to import xml fragment to an existing xelement?
I would prefer the way XElement.load("block.graphml"); This didn't work at all.
Thanks for your tips
You can do it like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
string input = File.ReadAllText(FILENAME);
XElement element = XElement.Parse("<Root xmlns:y=\"www.mynamespace.com\"></Root>");
element.Add(input);
}
}
}
Related
I have an XML file content as below
and I need to modify line 4:
701.50,24.0 to 701.50,30.0
How can I do this?
<CableLossConfig>
<Std Val="CATM1">
<Path Val="TX1">
<Loss>701.50,24.0</Loss>
<Loss>710.50,24.0</Loss>
<Loss>713.50,24.0</Loss>
<Loss>779.50,23.0</Loss>
<Loss>782.00,23.0</Loss>
<Loss>784.50,23.0</Loss>
<Loss>826.50,30.0</Loss>
<Loss>836.50,30.0</Loss>
<Loss>846.50,30.0</Loss>
<Loss>1712.50,37.0</Loss>
<Loss>1732.50,37.0</Loss>
<Loss>1752.50,37.0</Loss>
<Loss>1852.50,37.0</Loss>
<Loss>1880.00,37.0</Loss>
<Loss>1907.50,37.0</Loss>
</Path>
</Std>
</CableLossConfig>
Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement tx1 = doc.Descendants("Path").Where(x => (string)x.Attribute("Val") == "TX1").FirstOrDefault();
List<XElement> losses = tx1.Elements("Loss").ToList();
XElement loss1 = losses[1];
loss1.SetValue("701.50,30.0");
}
}
}
If you would like a simple solution that does not require creating a C# model representing the structure of the xml file, I would suggest using the XDocument .net class (https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument?view=netframework-4.8)
I found a quite nice example here on stackoverflow as well where a similar question was asked: Edit specific Element in XDocument
I hope this helps!
I am new to the UFT API Test, and I need to extract certain values from the XML response to be included in an existing XLS, which will serve as input data for another test.
This is my XML Response:
<NS1:Body>
<NS3:BuscaSaldosCaptacionOut xmlns:NS3="http://www.portal.com/ws/esb/ConsultaCuentasSaldos">
<SaldosCaptacion>
<NumeroCliente>51844068</NumeroCliente>
<Cuenta>0201484326</Cuenta>
<ProductoCuenta>01</ProductoCuenta>
<SubProductoCuenta>0382</SubProductoCuenta>
<Divisa>MXP</Divisa>
<IdCuenta>0201484326</IdCuenta>
<SaldoInicialDia>7062.42</SaldoInicialDia>
<SaldoPromedio>30596.01</SaldoPromedio>
<SaldoActual>17062.42</SaldoActual>
<SaldoDisponible>17062.42</SaldoDisponible>
<EstatusCuenta>A</EstatusCuenta>
</SaldosCaptacion>
<SaldosCaptacion>
<NumeroCliente>51844068</NumeroCliente>
<Cuenta>0201484371</Cuenta>
<ProductoCuenta>01</ProductoCuenta>
<SubProductoCuenta>0340</SubProductoCuenta>
<Divisa>MXP</Divisa>
<SaldoInicialDia>6825.11</SaldoInicialDia>
<SaldoPromedio>8936.26</SaldoPromedio>
<SaldoActual>6825.11</SaldoActual>
<SaldoDisponible>6825.11</SaldoDisponible>
<SaldoRetenido>0.00</SaldoRetenido>
<EstatusCuenta>A</EstatusCuenta>
</SaldosCaptacion>
<SaldosCaptacion>
<NumeroCliente>51844068</NumeroCliente>
<Cuenta>0201533729</Cuenta>
<ProductoCuenta>01</ProductoCuenta>
<SubProductoCuenta>0363</SubProductoCuenta>
<Divisa>MXP</Divisa>
<SaldoInicialDia>28316.52</SaldoInicialDia>
<SaldoPromedio>6230.52</SaldoPromedio>
<SaldoActual>7374.52</SaldoActual>
<SaldoDisponible>7374.52</SaldoDisponible>
<SaldoRetenido>942.00</SaldoRetenido>
<EstatusCuenta>A</EstatusCuenta>
</SaldosCaptacion>
</NS3:BuscaSaldosCaptacionOut>
I need save "Cuenta" and "SaldoActual" values. (Everybody), and completely ignore how to parameterize them.
The "Write to file" option does not work for me.
Try following code. If it doesn't work then the namespace needs to be changed in code. I can't tell the correct namespace because you did post the beginning of the xml file. I'm using xml linq which is a Net Library.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XElement doc = XElement.Parse(xml);
var results = doc.Descendants("SaldosCaptacion").Select(x => new {
Cuenta = (string)x.Element("Cuenta"),
SaldoActual = (decimal)x.Element("SaldoActual")
}).ToList();
}
}
}
I have been on google for a while but am just stumped. I need to parse xml of this nature. I can't seem to skip to elements in the middle, e.g. Folder. I have limited the xml as there were many 'Folder' elements. Any guidance would be appreciated. I was after the FolderID element's attribute ID.
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<h:ServerVersionInfo MajorVersion="14"
MinorVersion="1"
MajorBuildNumber="225"
MinorBuildNumber="46"
Version="Exchange2010_SP1"
xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<m:ResponseMessages>
<m:GetFolderResponseMessage ResponseClass="Success">
<m:ResponseCode>NoError</m:ResponseCode>
<m:Folders>
<t:Folder>
<t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
<t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
<t:DisplayName>Top of Information Store</t:DisplayName>
<t:TotalCount>0</t:TotalCount>
<t:ChildFolderCount>15</t:ChildFolderCount>
<t:EffectiveRights>
<t:CreateAssociated>true</t:CreateAssociated>
<t:CreateContents>true</t:CreateContents>
<t:CreateHierarchy>true</t:CreateHierarchy>
<t:Delete>true</t:Delete>
<t:Modify>true</t:Modify>
<t:Read>true</t:Read>
<t:ViewPrivateItems>true</t:ViewPrivateItems>
</t:EffectiveRights>
<t:PermissionSet>
<t:Permissions>
<t:Permission>
<t:UserId>
<t:DistinguishedUser>Default</t:DistinguishedUser>
</t:UserId>
<t:CanCreateItems>false</t:CanCreateItems>
<t:CanCreateSubFolders>false</t:CanCreateSubFolders>
<t:IsFolderOwner>false</t:IsFolderOwner>
<t:IsFolderVisible>false</t:IsFolderVisible>
<t:IsFolderContact>false</t:IsFolderContact>
<t:EditItems>None</t:EditItems>
<t:DeleteItems>None</t:DeleteItems>
<t:ReadItems>None</t:ReadItems>
<t:PermissionLevel>None</t:PermissionLevel>
</t:Permission>
<t:Permission>
<t:UserId>
<t:DistinguishedUser>Anonymous</t:DistinguishedUser>
</t:UserId>
<t:CanCreateItems>false</t:CanCreateItems>
<t:CanCreateSubFolders>false</t:CanCreateSubFolders>
<t:IsFolderOwner>false</t:IsFolderOwner>
<t:IsFolderVisible>false</t:IsFolderVisible>
<t:IsFolderContact>false</t:IsFolderContact>
<t:EditItems>None</t:EditItems>
<t:DeleteItems>None</t:DeleteItems>
<t:ReadItems>None</t:ReadItems>
<t:PermissionLevel>None</t:PermissionLevel>
</t:Permission>
</t:Permissions>
</t:PermissionSet>
<t:UnreadCount>0</t:UnreadCount>
</t:Folder>
</m:Folders>
</m:GetFolderResponseMessage>
</m:ResponseMessages>
</m:GetFolderResponse>
</s:Body>
</s:Envelope>
LINQ to XML is the best .NET XML Parsing API.
See
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/xdocument-class-overview
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConsoleApp12
{
class Program
{
static void Main(string[] args)
{
var doc = XDocument.Load(#"c:\temp\foo.xml");
var ns = (XNamespace)"http://schemas.microsoft.com/exchange/services/2006/types";
var folders = doc.Descendants(ns + "Folder");
foreach (var e in folders)
{
var folderId = e.Element(ns + "FolderId").Attribute("Id").Value;
Console.WriteLine(folderId);
}
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
}
You should learn about serlialization. It's very easy to convert an XML to and from a object in C#. https://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part
That said, this will get you the data you're after. It's not very reusable and won't help you with any xml files other than ones with one instance of that attribute, but it's what you're after so here you go.
string FolderId;
string ChangeKey;
using (StreamReader sr = new StreamReader("c:\\myfile.xml"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("<t:FolderId Id="))
{
try
{
var lineArray = line.Split('\"');
FolderId = lineArray[1];
ChangeKey = lineArray[3];
}
catch
{
// handle exception
}
}
}
}
You can use the XSD.exe to create a schema class. and then using XML deserializer, you can deserialize/parse xml to object
Using xml linq
XDocument doc = XDocument.Load(FILENAME);
List<XElement> folders = doc.Descendants().Where(x => x.Name.LocalName == "Folder").ToList();
XNamespace tNs = folders.FirstOrDefault().GetNamespaceOfPrefix("t");
XElement id_AAMkADk5MmY1ZThmLTM2MzAtNGVh = folders.Where(x => (string)x.Element(tNs + "FolderId").Attribute("Id") == "AAMkADk5MmY1ZThmLTM2MzAtNGVh").FirstOrDefault();
I am trying to grab the specific value of an attribute in:
http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com
<SD>
<POPULARITY URL="bing.com/" TEXT="16" SOURCE="panel"/>
<REACH RANK="16"/>
<RANK DELTA="-7"/>
<COUNTRY CODE="US" NAME="United States" RANK="9"/>
</SD>
</ALEXA>
I want to grab the value of
I have the current Console Code for this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string url = "http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(url);
XmlNode root = xmldoc.SelectSingleNode("//#RANK");
//XmlNamespaceManager xnm1 = new XmlNamespaceManager(xmldoc.NameTable);
//XmlNodeList nList1 = xmldoc.SelectNodes("//#RANK", xnm1);
Console.WriteLine(root.ToString());
Console.ReadLine();
}
}
}
But when I run it, I receive the following message in return:
System.Xml.XmlAttribute
What am I doing wrong?
Try changing:
Console.WriteLine(root.ToString());
to:
Console.WriteLine(root.Value);
Hope that helps.
The XML file is like this,There are about 20 Nodes(modules) like this.
<list>
<module code="ECSE502">
<code>ECSE502</code>
<name>Algorithms and Data structures</name>
<semester>1</semester>
<prerequisites>none</prerequisites>
<lslot>0</lslot>
<tslot>1</tslot>
<description>all about algorythms and data structers with totorials and inclass tests</description>
</module>
</list>
I did the following code. But when I debugged it it even didn't went inside to foreach function.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ModuleEnrolmentCW
{
class XMLRead
{
public string[] writeToXML(string s)
{
string text = s;
string[] arr = new string[6];
XmlDocument xml = new XmlDocument();
xml.Load("modules.xml");
XmlNodeList xnList = xml.SelectNodes("list/module[#code='" + text + "']");
foreach (XmlNode xn in xnList)
{
arr[0] = xn.SelectSingleNode("code").InnerText;
arr[1] = xn.SelectSingleNode("name").InnerText;
arr[2] = xn.SelectSingleNode("semester").InnerText;
arr[3] = xn.SelectSingleNode("prerequisites").InnerText;
arr[4] = xn.SelectSingleNode("lslot").InnerText;
arr[5] = xn.SelectSingleNode("tslot").InnerText;
}
return arr;
}
}
}
Please tell me where is the wrong??
Here is the rest of the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ModuleEnrolmentCW
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string selected;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
XMLRead x = new XMLRead();
selected = (string)listBox1.SelectedItem;
string[] arr2 = x.writeToXML(selected);
label11.Text = arr2[0];
}
}
}
Make sure you are specifying correct path for your xml file.
It is working for me.
This line:
XmlNodeList xnList = xml.SelectNodes("list/module[#code='" + text + "']");
should read:
XmlNodeList xnList = xml.SelectNodes("list/module"); //Does not answer full scope of the question
Edit following a reread of the question:
The OP's code works fine in my tests. Either the file path is not correct, or the the string s passed into text matches the case of the Code value by which you are reading the nodes.
The SelectNodes XPath as you have it is case sensitive.
You appear to be working with XPath V1.0 which doesn't appear to support out of the box case insensitivity if that's a issue. See this link for a way to perform case insensitive XPath searches: http://blogs.msdn.com/b/shjin/archive/2005/07/22/442025.aspx
See also this link: case-insensitive matching in xpath?
Your code is correct, if the input is really the one you shown, and s point to an actual present code. Since you are pointing the file by a relative path, ensure you are loading the file you really expect.
Found the error. I was passing a wrong value to writeToXML method. Insted of passing code, I have passed name