How to get innertext in an XML - c#

I have the following XML file
<?xml version="1.0" encoding="utf-8"?>
<Comprobante version="2.2" serie="A" folio="35207" fecha="2013-05-31T11:51:48">
<Emisor rfc="" nombre="E">
<DomicilioFiscal calle="" noExterior="" colonia="" />
<ExpedidoEn calle="" noExterior="" colonia="" />
<RegimenFiscal Regimen="Regimen" />
</Emisor>
<Receptor rfc="" nombre="Z">
<Domicilio calle="" noExterior="" colonia="" />
</Receptor>
<Conceptos cantidad="1.000" unidad="COMISION" descripcion="PENDIENTE" valorUnitario="28.50000" importe="28.50" />
<Impuestos totalImpuestosTrasladados="3.14">
<Traslados>
<Traslado impuesto="IVA" tasa="11.00" importe="3.14" />
</Traslados>
</Impuestos>
<Addenda>
<ener:EstadoDeCuentaCombustible xmlns:ener="">
<ener:cadenaOriginal>||2.2|A|35207|2013-05-31T11:51:48|773463|2011|ingreso|Pago en una sola exhibicion|28.50|31.64|Tarjeta|Tijuana,Baja California|3213|ERE|E S.A. de C.V.|Prol|13351|Anexa e|Tijuana|Tijuana|Baja California|Mexico|22100|Prol|13351|Anexa e|Tijuana|Tijuana|Baja California|Mexico|22100|Regimen|XA|Z||||TIJUANA|TIJUANA|BAJA CALIFORNIA|Mexico||1.000|COMISION|PENDIENTE|28.50000|28.50|IVA|11.00|3.14|3.14||</ener:cadenaOriginal>
<ener:idRefund>98</ener:idRefund>
</ener:EstadoDeCuentaCombustible>
</Addenda>
</Comprobante>
I need to get the text that is inside (that long string)
Here's how I start the c# code
XmlDocument doc = new XmlDocument();
doc.Load("Route");
XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
xnm.AddNamespace("Documento", "http://www.sat.gob.mx/cfd/2");
xnm.AddNamespace("ener", "http://www.enercard.com.mx/cfd");
I've tried various ways...
//strOriginalString = doc.DocumentElement.SelectSingleNode("//Documento:Addenda", xnm).FirstChild.SelectSingleNode("//ener:cadenaOriginal", xnm).InnerText;
//strOriginalString = doc.DocumentElement.SelectSingleNode("//Documento:Addenda//ener:EstadoDeCuentaCombustible", xnm).FirstChild.SelectSingleNode("//ener:cadenaOriginal", xnm).InnerText;
//strOriginalString = doc.DocumentElement.SelectSingleNode("//Documento:Addenda/Documento:cadenaOriginal", xnm).InnerXml;
this 3 ways always throw an exception...
I found another way that doesn't throw an exception, but it doesn't get the string
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("/Addenda/EstadoDeCuentaCombustible");
strOriginalString = "";
foreach (XmlNode node in nodes)
{
XmlNode child = node.SelectSingleNode("./cadenaOriginal");
if (child != null)
{
strOriginalString = child.InnerText;
break;
}
}
What am I doing wrong? or is there another way that I can get the string inside

This is somewhat simplified, and you'll need to deal with the namespace problems (one I note below), but otherwise, this is the basic construct:
XmlDocument doc = new XmlDocument();
try { doc.Load("c:\\temp\\test.xml"); }
catch (Exception ex) { }
XmlElement root = doc.DocumentElement;
String strOriginalString = "";
foreach (XmlNode node in root.SelectNodes("/Comprobante/Addenda"))
{
XmlNode child = node.SelectSingleNode("EstadoDeCuentaCombustible/cadenaOriginal");
if (child != null)
{
strOriginalString = child.InnerText;
break;
}
}
There's an issue with <ener:EstadoDeCuentaCombustible xmlns:ener=""> as the empty namespace is invalid.

You're missing xmlns:ener declaration on your XML document:
<ener:EstadoDeCuentaCombustible xmlns:ener="http://www.enercard.com.mx/cfd">
Fix that and you'll be able to use something like this:
string xpath = "/Comprobante/Addenda/ener:EstadoDeCuentaCombustible";
foreach (XmlNode estado in doc.SelectNodes(xpath, xnm))
{
Console.WriteLine("ener:cadenaOriginal={0}",
estado.SelectSingleNode("ener:cadenaOriginal", xnm).InnerText);
}

I find Linq2Xml easier to use. (Assuming you have a valid namespace in xmlns:ener="").
var xDoc = XDocument.Load(filename);
XNamespace ener = "your name space for ex ,http://www.enercard.com.mx/cfd";
var result = xDoc.Descendants(ener + "cadenaOriginal").First().Value;

Your second attempt looks the closest to what should work:
//strOriginalString = doc.DocumentElement.SelectSingleNode("//Documento:Addenda//ener:EstadoDeCuentaCombustible", xnm).FirstChild.SelectSingleNode("//ener:cadenaOriginal", xnm).InnerText;
But switch to this(edited):
//strOriginalString = doc.SelectSingleNode("//ener:cadenaOriginal", xnm).InnerText;

Related

XDocument attribute of existing node does not exist [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm pulling in an XML set from a web service, loading it into XDocument and then parsing it out. On one node, the attribute, which is CLEARLY there if I output the XML to a file, is telling me that it doesn't exist. And I cannot figure out what stupid thing I'm doing to cause this error.
<?xml version="1.0" encoding="utf-8"?>
<MESSAGE xmlns="http://www.mismo.org/residential/2009/schemas_v1_4_2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DEAL_SETS>
<DEAL_SET>
<DEALS>
<DEAL>
<ASSETS>
<OWNED_PROPERTIES>
<OWNED_PROPERTY SequenceNumber="1">
<OWNED_PROPERTY_DETAIL>
<PropertyUsageType>PrimaryResidence</PropertyUsageType>
</OWNED_PROPERTY_DETAIL>
</OWNED_PROPERTY>
<OWNED_PROPERTY SequenceNumber="2">
<OWNED_PROPERTY_DETAIL>
<PropertyUsageType>PrimaryResidence</PropertyUsageType>
</OWNED_PROPERTY_DETAIL>
</OWNED_PROPERTY>
</OWNED_PROPERTIES>
</ASSETS>
<COLLATERALS>
<COLLATERAL SequenceNumber="1">
<COLLATERAL_DETAIL>
<LienPriorityExceptionType>FirstLien</LienPriorityExceptionType>
</COLLATERAL_DETAIL>
<PROPERTIES>
<PROPERTY>
<FLOOD_DETERMINATION>
<FLOOD_DETERMINATION_DETAIL/>
</FLOOD_DETERMINATION>
<IMPROVEMENT>
<UNIT_GROUPS>
<UNIT_GROUP>
<UNIT_GROUP_DETAIL>
<UnitType>UnitOne</UnitType>
</UNIT_GROUP_DETAIL>
<ROOM_TYPE_SUMMARY/>
</UNIT_GROUP>
</UNIT_GROUPS>
</IMPROVEMENT>
</PROPERTY>
</PROPERTIES>
</COLLATERAL>
<COLLATERAL SequenceNumber="5">
<COLLATERAL_DETAIL>
<LienPriorityExceptionType>FirstLien</LienPriorityExceptionType>
</COLLATERAL_DETAIL>
<PROPERTIES>
<PROPERTY>
<FLOOD_DETERMINATION>
<FLOOD_DETERMINATION_DETAIL/>
</FLOOD_DETERMINATION>
<IMPROVEMENT>
<UNIT_GROUPS>
<UNIT_GROUP>
<UNIT_GROUP_DETAIL>
<UnitType>UnitOne</UnitType>
</UNIT_GROUP_DETAIL>
<ROOM_TYPE_SUMMARY/>
</UNIT_GROUP>
</UNIT_GROUPS>
</IMPROVEMENT>
</PROPERTY>
</PROPERTIES>
</COLLATERAL>
</COLLATERALS>
</DEAL>
</DEALS>
</DEAL_SET>
</DEAL_SETS>
</MESSAGE>
My code can find the SequenceNumber value of OWNED_PROPERTY just fine, but blows up on COLLATERAL:
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Generic;
XDocument resx = new XDocument();
public override void MethodInternal()
{
string uid = "something";
string pwd = "somethingelse";
string httppath = "url";
try
{
NetworkCredential cred = new NetworkCredential(uid, pwd);
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(httppath), "NTLM", cred);
WebRequest client = WebRequest.Create(httppath);
client.Credentials = credCache;
client.Method = "GET";
client.ContentType = "application/xml";
WebResponse resp = client.GetResponse();
Stream respStream = resp.GetResponseStream();
StreamReader strrdr = new StreamReader(respStream);
string allxml = strrdr.ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(fullstr);
XNamespace ns = "http://www.mismo.org/residential/2009/schemas_v1_4_2";
resx = XDocument.Parse(allxml);
strrdr.Close();
respStream.Close();
resp.Close();
int seqnum = 0;
int cseqnum = 0;
foreach (XElement b in resx.Root.Descendants(ns + "DEAL"))
{
// Primary node: ASSETS
if (b.Elements(ns + "ASSETS").Any())
{
IEnumerable<XElement> axl = b.Descendants(ns + "ASSETS");
foreach (var axcol in axl.Elements())
{
seqnum = 0;
IEnumerable<XElement> opxl = b.Descendants(ns + "OWNED_PROPERTY");
foreach (var opxlcol in axl.Elements())
{
seqnum = int.Parse(opxlcol.Element(ns + "OWNED_PROPERTY").Attribute("SequenceNumber").Value.ToString());
IEnumerable<XElement> opxls = opxlcol.Descendants(ns + "OWNED_PROPERTY");
foreach (var opxlsc in opxls.Elements())
{
if (opxlsc.Elements(ns + "PropertyUsageType").Any())
//occa.Add(seqnum, opxlsc.Element(ns + "PropertyUsageType").Value.ToString());
}
} // OWNED_PROPERTY XElements
} // XElements under ASSETS
} // test to make sure ASSETS exists
// Primary node: COLLATERALS
if (b.Elements(ns + "COLLATERALS").Any())
{
IEnumerable<XElement> colsxl = b.Descendants(ns + "COLLATERALS");
foreach (var clsxl in colsxl.Elements())
{
cseqnum = 0;
IEnumerable<XElement> clxl = clsxl.DescendantsAndSelf(ns + "COLLATERAL");
foreach (var clxll in clxl.Elements())
{
//System.Windows.Forms.MessageBox.Show(ns.ToString() + clsxl.Name.LocalName.ToString());
//if (clsxl.Name.LocalName.ToString() == "COLLATERAL")
//{
bool bv = resx.Descendants("COLLATERAL").Select(x => (int?)x.Attribute("SequenceNumber")).FirstOrDefault(x => x != null) > 0;
System.Windows.Forms.MessageBox.Show(bv.ToString());
System.Windows.Forms.MessageBox.Show(clsxl.Element(ns + "COLLATERAL").Attribute("SequenceNumber").Value.ToString());
cseqnum = int.Parse(clsxl.Element(ns + "COLLATERAL").Attribute("SequenceNumber").Value.ToString());
//}
if (clxll.Elements(ns + "LienPropertyExceptionType").Any())
//liena.Add(cseqnum, clxll.Element(ns + "LienPropertyExceptionType").Value.ToString());
IEnumerable<XElement> pxl = clsxl.Descendants(ns + "PROPERTY");
foreach (var p in pxl.Elements())
{
if (p.Elements(ns + "IMPROVEMENT").Any())
{
IEnumerable<XElement> ig = p.Descendants(ns + "IMPROVEMENT");
foreach (var igxl in ig.Elements())
{
if (igxl.Elements(ns + "UnitType").Any())
//nua.Add(cseqnum, igxl.Element(ns + "UnitType").Value.ToString());
//} // XElements under UNIT_GROUP_DETAIL
} // XElements under IMPROVEMENT
} // test to make sure IMPROVEMENT exists
} // XElements under PROPERTY
} // XElements in COLLATERAL
} // XElements under COLLATERALS
} // test to make sure COLLATERALS exists
} // root
}
catch (Exception ex)
{
//handle exception
}
}
So where am I going wrong? The only diffs other than textual in the XML are that the OWNED_PROPERTY tag is under an additional tag, while is directly beneath . But as you can see my code is skipping past the tag, as it's useless for my purposes.
OK, so your variable names are clsxl, clxll, clxl, chicxulub, mxyzptlk, and lerxst. Sensible enough.
This line threw an exception. Somewhere lost in the depths of that expression, something's returning null. Well, you can't debug that by pasting the whole thing in between the parens of a call to MessageBox.Show(), because the whole point is it throws an exception instead of returning a value.
//System.Windows.Forms.MessageBox.Show(clsxl.Element(ns + "COLLATERAL").Attribute("SequenceNumber").Value.ToString());
cseqnum = int.Parse(clsxl.Element(ns + "COLLATERAL").Attribute("SequenceNumber").Value.ToString());
Here's what you do: Break it down into the simplest possible expressions and see what returns what. Takes a while, but so does reading all those comments from people moaning about variable declarations.
var element = clsxl.Element(ns + "COLLATERAL");
var attr = element.Attribute("SequenceNumber");
// attr.Value is already a string. If it's anything.
cseqnum = int.Parse(attr.Value);
Set a breakpoint on the first of those lines, and hover the mouse over everything as you go.
What you'll find is that clsxl is "COLLATERAL". It has no child named "COLLATERAL" with a "SequenceNumber" attribute. It has the "SequenceNumber" attribute.
// Ain't no such animal
var element = clsxl.Element(ns + "COLLATERAL");
clsxl is the parent loop variable. That's "COLLATERAL". That's the one you want.
var attr = clsxl.Attribute("SequenceNumber");
cseqnum = int.Parse(attr.Value);
I have a gut feeling you could lose 50% of this code and sleep easier, but I didn't try to tease out the intent of every little bit, so that could be a high estimate.
In all seriousness, I do understand where you're getting those names from. They're not noise, they're based on the XML element names. However, I would be calling them xnCollateral and so on. The extra typing pays for itself. Those very compact '70s C style identifiers were a reasonable compromise when we had 80x25 characters on a VT100, but we've all got much bigger screens now.
Your XML document have a default namespace, so all navigation operations must use it. You done right in most places, but you're missing the namespace in lines like:
bool bv = resx.Descendants("COLLATERAL")

Malformed reference element signing a xml file of bills

I'm developing a program to digitally sign invoices in xml. I followed this guide https://www.profissionaisti.com.br/2010/07/assinando-digitalmente-um-xml-usando-c/#comment-197297. However, i'm getting an error Malformed reference element.
The code is :
static void Main(string[] args)
{
//open certificates of current user
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
//Open screen to choose certificate
var selectedCertificate = X509Certificate2UI.SelectFromCollection(
store.Certificates,
"Title",
"MSG",
X509SelectionFlag.SingleSelection);
//Gets the x509 object of the selected certificate
foreach (X509Certificate2 x509 in selectedCertificate)
{
try
{
//==============================
// Start reading xml files
//==============================
var txtFiles = Directory.EnumerateFiles("./", "*.xml");
foreach (string currentFile in txtFiles)
{
Console.WriteLine("Reading file " + currentFile + ":");
var originalDoc = XDocument.Load(currentFile);
XmlDocument doc = DocumentExtensions.ToXmlDocument(originalDoc);
//==============================
// Start reading bills
//==============================
Get the xml node InfRps, which is a representation of the bill in xml:
XmlNodeList ListInfRps = doc.GetElementsByTagName("InfRps");
int NodeCounter = 1;
foreach (XmlElement InfRps in ListInfRps)
{
There is a class on namespace System.Security.Cryptography.Xml of the .NET framework called SignedXml, that implements the W3C standard for signature of documents and verification of signed documents. The code below initiate this class.
string id = InfRps.Attributes.GetNamedItem("Id").Value;
SignedXml signedXml = new SignedXml(InfRps);
signedXml.SigningKey = x509.PrivateKey;
Acording to the IRS, the XML must be put in canonical form before processing. The class Reference takes care of this part of the process, including the identification of the node infNFE and the demanded transformation:
// Transformation for DigestValue
Reference reference = new Reference("#" + id);
//Reference reference = new Reference("#" + "lote");
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigC14NTransform());
signedXml.AddReference(reference);
Before computing the signature, we must configure the treatment of the information of the digital certificate used. Based of this data the IRS is able to validate the signature and be certain that no information was modified after the sender of the bill signed it. We must include a clause with the data of the certificate.
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(x509));
signedXml.KeyInfo = keyInfo;
Now, we should compute the signature: And here is the error.
signedXml.ComputeSignature();
If computing the signature works, than we can create the element signature on the xml:
XmlElement xmlSignature = doc.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#");
XmlAttribute attr = doc.CreateAttribute("Id");
attr.Value = "Ass_" + id;
//Add the attribute to the node
xmlSignature.Attributes.SetNamedItem(attr);
XmlElement xmlSignedInfo = signedXml.SignedInfo.GetXml();
XmlElement xmlKeyInfo = signedXml.KeyInfo.GetXml();
XmlElement xmlSignatureValue = doc.CreateElement("SignatureValue", xmlSignature.NamespaceURI);
string signBase64 = Convert.ToBase64String(signedXml.Signature.SignatureValue);
XmlText text = doc.CreateTextNode(signBase64);
xmlSignatureValue.AppendChild(text);
xmlSignature.AppendChild(doc.ImportNode(xmlSignedInfo, true));
xmlSignature.AppendChild(xmlSignatureValue);
xmlSignature.AppendChild(doc.ImportNode(xmlKeyInfo, true));
XmlNodeList ListRps = doc.GetElementsByTagName("Rps");
int RpsCounter = 1;
foreach (XmlElement Rps in ListRps)
{
if (RpsCounter == NodeCounter)
{
Rps.AppendChild(xmlSignature);
}
RpsCounter++;
}
Console.WriteLine("Ok");
NodeCounter++;
}
(...)
I get CryptographicException: Malformed reference element:
System.Security.Cryptography.CryptographicException: Malformed reference element.
at System.Security.Cryptography.Xml.Reference.CalculateHashValue(XmlDocument
document, CanonicalXmlNodeList refList)
at System.Security.Cryptography.Xml.SignedXml.BuildDigestedReferences()
at System.Security.Cryptography.Xml.SignedXml.ComputeSignature()
at escolhercertificadosimples.Program.Main(String[] args) in
C:\Users\user\Do
cuments\Visual Studio
2015\Projects\assinaturalote\assinaturalote\Program.cs:line 143
Pressione qualquer tecla para continuar. . .
An example of xml to sign is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<EnviarLoteRpsEnvio xmlns="http://www.abrasf.org.br/nfse.xsd">
<LoteRps Id="lote" versao="1.00">
<NumeroLote>8</NumeroLote>
<Cnpj>09419261123115</Cnpj>
<InscricaoMunicipal>51624621</InscricaoMunicipal>
<QuantidadeRps>1</QuantidadeRps>
<ListaRps>
<Rps xmlns="http://www.abrasf.org.br/nfse.xsd">
<InfRps Id="rps:8201603150148">
<IdentificacaoRps>
<Numero>8201613150148</Numero>
<Serie>248</Serie>
<Tipo>2</Tipo>
</IdentificacaoRps>
<DataEmissao>2016-03-15T18:18:39</DataEmissao>
<NaturezaOperacao>1</NaturezaOperacao>
<OptanteSimplesNacional>2</OptanteSimplesNacional>
<IncentivadorCultural>2</IncentivadorCultural>
<Status>1</Status>
<Servico>
<Valores>
<ValorServicos>20.00</ValorServicos>
<ValorDeducoes>0.00</ValorDeducoes>
<ValorPis>1.60</ValorPis>
<ValorCofins>2.00</ValorCofins>
<ValorInss>0.00</ValorInss>
<ValorIr>3.00</ValorIr>
<ValorCsll>2.00</ValorCsll>
<IssRetido>1</IssRetido>
<OutrasRetencoes>0.00</OutrasRetencoes>
<DescontoIncondicionado>0.00</DescontoIncondicionado>
<DescontoCondicionado>0.00</DescontoCondicionado>
</Valores>
<ItemListaServico>1.07</ItemListaServico>
<CodigoTributacaoMunicipio>10700100</CodigoTributacaoMunicipio>
<Discriminacao>test.</Discriminacao>
<CodigoMunicipio>4314902</CodigoMunicipio>
</Servico>
<Prestador>
<Cnpj>09419261000115</Cnpj>
<InscricaoMunicipal>51624621</InscricaoMunicipal>
</Prestador>
<Tomador>
<IdentificacaoTomador>
<CpfCnpj>
<Cnpj>14525684000150</Cnpj>
</CpfCnpj>
</IdentificacaoTomador>
<RazaoSocial>test S.A.</RazaoSocial>
<Endereco>
<Endereco>Rua test</Endereco>
<Numero>83</Numero>
<Complemento>Sala test</Complemento>
<Bairro>Centro</Bairro>
<CodigoMunicipio>3304557</CodigoMunicipio>
<Uf>RJ</Uf>
<Cep>20091007</Cep>
</Endereco>
<Contato>
<Telefone>2136261100</Telefone>
<Email>test#test.com.br</Email>
</Contato>
</Tomador>
</InfRps>
</Rps>
</ListaRps>
</LoteRps>
</EnviarLoteRpsEnvio>
Anybody has any idea? Any idea would be apreciated
You have a colon in your Id value (rps:8201603150148), which is illegal for an identifier attribute. (Per https://www.w3.org/TR/xml-id/#processing, The normalized value of the attribute is an NCName..., where the "NC" part of "NCName" is "no-colon")
Since there's a colon in the Id value SignedXml won't resolve it, so it says your reference points to nowhere.
If you are writing new code and have no requirement on your (technically malformed) identifier attribute values, the best answer is to get rid of the colons (underscore usually serves well in this role).
Since conforming to the xml:id constraints makes for the most interoperable document, that's definitely the best answer.
The next best answer is to extend the SignedXml class and override GetIdElement. You should make your match logic as strict as possible. Note that this logic has to be performed on both the signer and reciever... and is only valid as long as both sides have the ability to accept loose conformance documents.
internal class RpsSignedXml : SignedXml
{
// ctors and other members as appropriate
public override XmlElement GetIdElement(XmlDocument document, string idValue)
{
if (document == null)
return null;
if (string.IsNullOrEmpty(idValue))
return null;
if (!idValue.StartsWith("rps:"))
return base.GetIdElement(document, idValue);
string xPath = $"//InfRps[#Id=\"{idValue}\"]";
XmlNodeList nodeList = document.SelectNodes(xPath);
if (nodeList == null || nodeList.Count != 1)
return null;
return nodeList[0] as XmlElement;
}
}
I have a similar problem. I get this exception:
Unable to resolve Uri cid:Part-0986dfc9-2748-41a4-8624-e505e98b29be.
System.Security
at System.Security.Cryptography.Xml.Reference.CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
at System.Security.Cryptography.Xml.SignedXml.BuildDigestedReferences()
at System.Security.Cryptography.Xml.SignedXml.ComputeSignature()
at EmpTestWeb.BL.ebXMLSigner.ComputeSig(X509Certificate2 cert, XmlDocument doc, String externalReferenceUri) in C:\Websites\TestWeb\BL\ebXMLSigner.cs:line 67
at ASP.ebxml_aspx.GenerateHeaderXML() in c:\Websites\TestWeb\ebXML.aspx:line 227
at ASP.ebxml_aspx.btnSubmit_Click(Object sender, EventArgs e) in c:\Websites\TestWeb\ebXML.aspx:line 89
It doesnt help if I try to use this class:
class ebXMLSignedXml : SignedXml
{
// ctors and other members as appropriate
public ebXMLSignedXml(XmlDocument doc) : base(doc) { }
public override XmlElement GetIdElement(XmlDocument document, string idValue)
{
if (document == null)
return null;
if (string.IsNullOrEmpty(idValue))
return null;
if (!idValue.StartsWith("cid:"))
return base.GetIdElement(document, idValue);
string xPath = $"//InfRps[#Id=\"{idValue}\"]";
XmlNodeList nodeList = document.SelectNodes(xPath);
if (nodeList == null || nodeList.Count != 1)
return null;
return nodeList[0] as XmlElement;
}
}
it never reaches where it should select the element with Id="cid:...."
SOLUTION
I ended up passing a stream of the content instead of the URI instead and added the URI="cpa:13131312" attribute manually to the generated XML.
In my case, after days trapped. It was the Reference.uri. I was saving it as "#1" and it cannot start with a number, I left it in "#test" as well as the ID of the XML to sign. I had it "1" and I left it on "test".
https://stackoverflow.com/a/64154967/1536197

how to edit the nlog config file programmatically

i am trying to edit the logging level in the config file programmaticly.
foreach (var rule in LogManager.Configuration.LoggingRules)
{
if (m_loginglevelcomboBox.SelectedItem.ToString() == "Debug")
{
rule.EnableLoggingForLevel(LogLevel.Debug);
}
else
{
rule.EnableLoggingForLevel(LogLevel.Info);
}
}
//LogManager.ReconfigExistingLoggers();
I am not interested in calling the Reconfig,as the changes will affect the application on the fly.
I want the changes to be made when the application is restarted. so I need it to edit the config file.
i cant use xDocument ,as linq is not compatible with my .net version
so how can i edit the minlevel rule to debug/info ?
i used this to edit the logging level. I hope if this would help if some one stumbles across. If some one thinks it to be a bad idea, please let me know .
string configFilename = GetConfigFilePath();
XmlDocument doc = new XmlDocument();
doc.Load(configFilename);
XmlNode documentElement = doc.DocumentElement;
foreach (XmlNode node in documentElement.ChildNodes)
{
if (ruleDocumentNodeName.Equals(node.Name))
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (loggerDocumentNodeName.Equals(childNode.Name))
{
XmlAttribute idAttribute = childNode.Attributes[minLevelAttributeName];
string currentValue = minLogingLevelComboBox.SelectedItem.ToString();
idAttribute.Value = currentValue;
doc.Save(configFilename);
MinLoggingLevelChanged = true;
}
}
}
}

Why doesn't my code want to add any more child nodes? (XML)

I'm coding a program to translate a game. The original string and the translated string get saved to an XmlDocument, which can be saved to a file when the user clicks a button.
Everything works fine until a certain number of nodes (30?) or until it reaches a certain size (8192 bytes?), then it just stops adding nodes to the XmlDocument.
My code: http://lesderid.pastebin.com/zgcT9PVu.
An XML file: #character.lua.Decoded.VOQ.xml
There doesn't seem to be any problem i tried your code and i got correct output.. so problem is somewhere else.
I tried this (In LINQPAD) and Got 100 Elements (10,349 Bytes)
XmlDocument XmlDoc;
XmlElement mainStringsNode;
void Main()
{
XmlDoc = new XmlDocument();
XmlNode xmlDeclarationNode = XmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlDoc.AppendChild(xmlDeclarationNode);
mainStringsNode = XmlDoc.CreateElement("Strings");
XmlDoc.AppendChild(mainStringsNode);
var docWriter = new StringWriter();
XmlDoc.Save(docWriter);
for(int i=0; i < 100; i++) AddStringChild(i, "satr", "edited");
XmlDoc.Dump();
}
private void AddStringChild(int id, string originalString, string editedString)
{
XmlNode stringNode = XmlDoc.CreateElement("String");
var posAttribute = XmlDoc.CreateAttribute("position");
posAttribute.Value = id.ToString();
if (stringNode.Attributes != null) stringNode.Attributes.Append(posAttribute);
mainStringsNode.AppendChild(stringNode);
var originalStringNode = XmlDoc.CreateElement("OriginalString");
originalStringNode.AppendChild(XmlDoc.CreateTextNode(originalString));
stringNode.AppendChild(originalStringNode);
var editedStringNode = XmlDoc.CreateElement("EditedString");
editedStringNode.AppendChild(XmlDoc.CreateTextNode(editedString));
stringNode.AppendChild(editedStringNode);
}
Output:
<?xml version="1.0" encoding="UTF-8"?><Strings><String position="0"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="1"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="2"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="3"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="4"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="5"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="6"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="7"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="8"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="9"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="10"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="11"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="12"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="13"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="14"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="15"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="16"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="17"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="18"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="19"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="20"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="21"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="22"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="23"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="24"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="25"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="26"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="27"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="28"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="29"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="30"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="31"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="32"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="33"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="34"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="35"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="36"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="37"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="38"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="39"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="40"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="41"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="42"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="43"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="44"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="45"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="46"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="47"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="48"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="49"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="50"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="51"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="52"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="53"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="54"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="55"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="56"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="57"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="58"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="59"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="60"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="61"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="62"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="63"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="64"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="65"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="66"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="67"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="68"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="69"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="70"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="71"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="72"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="73"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="74"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="75"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="76"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="77"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="78"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="79"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="80"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="81"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="82"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="83"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="84"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="85"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="86"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="87"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="88"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="89"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="90"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="91"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="92"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="93"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="94"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="95"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="96"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="97"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="98"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String><String position="99"><OriginalString>satr</OriginalString><EditedString>edited</EditedString></String></Strings>

Test for root node XML .NET

I'm currently using the code below to attempt to check for a certain root node (rss) and a certain namespace\prefix (itunes), but it seems to be saying that the feed is valid even when supplied with a random web page URL instead of one pointing to a feed.
FeedState state = FeedState.Invalid;
XmlDocument xDoc = new XmlDocument();
xDoc.Load(_url);
XmlNode root = xDoc.FirstChild;
if (root.Name.ToLower() == "rss" && root.GetNamespaceOfPrefix("itunes") == "http://www.itunes.com/dtds/podcast-1.0.dtd")
{
state = FeedState.Valid;
}
return state;
Can anybody tell me why this might be?
Found the solution now. Putting xDoc.Load(_url); in a try .. catch block and returning FeedState.Invalid upon exception seems to have solved my problems.
FeedState state = FeedState.Invalid;
XmlDocument xDoc = new XmlDocument();
try
{
xDoc.Load(_url);
}
catch
{
return state;
}
XmlNode root = xDoc.FirstChild;
if (root.Name.ToLower() == "rss" && root.GetNamespaceOfPrefix("itunes") == "http://www.itunes.com/dtds/podcast-1.0.dtd")
{
state = FeedState.Valid;
}
return state;

Categories

Resources